question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
72,457,380 | 72,457,456 | stack overflow, when i using Detours to intercept CreateFileW | i want to intercept win32 api CreateFileW, but i meet an error "stack overflow". i don't know what happend, can someone help me?
error:
Exception thrown at 0x00007FFA76204170 (KernelBase.dll) in detoursExample.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000094A6A03FF0).
Unhandled exception at 0x00007FFA76204170 (KernelBase.dll) in detoursExample.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x00000094A6A03FF0).
#include <Windows.h>
#include <string>
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include"detours.h"
#pragma comment(lib,"detours.lib")
void myCreateFile(LPCWSTR pathName) {
// Open a handle to the file
HANDLE hFile = CreateFileW(
pathName, // L".\\NewFile.txt", // Filename
GENERIC_WRITE, // Desired access
FILE_SHARE_READ, // Share mode
NULL, // Security attributes
CREATE_NEW, // Creates a new file, only if it doesn't already exist
FILE_ATTRIBUTE_NORMAL, // Flags and attributes
NULL); // Template file handle
if (hFile == INVALID_HANDLE_VALUE)
{
// Failed to open/create file
throw("failed to open/create file\n");
return ;
}
// Write data to the file
std::string strText = "Hello World!"; // For C use LPSTR (char*) or LPWSTR (wchar_t*)
DWORD bytesWritten;
WriteFile(
hFile, // Handle to the file
strText.c_str(), // Buffer to write
strText.size(), // Buffer size
&bytesWritten, // Bytes written
nullptr); // Overlapped
// Close the handle once we don't need it.
CloseHandle(hFile);
}
HANDLE (*oldCreateFile)(LPCWSTR,
DWORD,
DWORD,
LPSECURITY_ATTRIBUTES,
DWORD,
DWORD,
HANDLE) = CreateFileW;
HANDLE WINAPI newCreateFile(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
) {
printf("hook success!\n");
return CreateFileW(
//L".\\newFiles.txt", // L".\\NewFile.txt", // Filename
lpFileName,
dwDesiredAccess, // Desired access
dwShareMode, // Share mode
lpSecurityAttributes, // Security attributes
dwCreationDisposition, // Creates a new file, only if it doesn't already exist
dwFlagsAndAttributes, // Flags and attributes
hTemplateFile);
}
void hook() {
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
//DetourAttach((void**)&poldsystem, newsystem);
DetourAttach((void**)&oldCreateFile, newCreateFile);
DetourTransactionCommit();
}
int main() {
hook();
myCreateFile(L".\\text.txt");
getchar();
return 0;
}
| In newCreateFile, you need to call oldCreateFile, not CreateFileW. The way you're doing it, your hook ends up calling into itself forever.
|
72,458,092 | 72,463,889 | Can't figure out how to pass arguments to a bind function | After several tries of trying to pass arguments in a scroll event function, It's not working.
I'm making a custom scroll panel and need the bind function to trigger when the user scrolls down, in order to do that I need to pass variables that are going to be used inside the panel. This wasn't an issue with the wxScrolledWindow since I didn't have to bind anything and could just make a function for it and call it directly.
Some of these arguments I don't necessarily need to pass in as I can get them by using event.GetEventObject(); but the rest like m which is a map I need to pass on.
Among the solutions I've tried shown below, I thought of making a hidden panel with the map already inside or near the "scroll panel" so I can access it using the event.GetEventObject(); but I'm leaving it as a last-ditch effort (if that would even work). I'm really hoping there's an easier way. Any help is appreciated.
Attempt #1
ScrolledWindow->Bind(wxEVT_SCROLLWIN_PAGEDOWN, &MyFrame::ScrolledWindowCreate, this)(m, ScrolledWindow, ScrolledWindowMain, ScrolledWindowSizer, initalWindowWidth));
Attempt #2
// Saw a thread that said parameters should be put outside
ScrolledWindow->Bind(wxEVT_SCROLLWIN_PAGEDOWN, &MyFrame::ScrolledWindowCreate, this)(m, ScrolledWindowContainerSub, ScrolledWindowMain, ScrolledWindowSizer, initalWindowWidth);
Attempt #3
// Tried to pass the arguments as the userData as in the WxWidgets documentation, the WxWidgets forums suggested it, but I looked and apparently, I need to pass in a wxObject? I don't know how a set of arguments is supposed to be turned into a wxObject
ScrolledWindow->Bind(wxEVT_SCROLLWIN_PAGEDOWN, &MyFrame::ScrolledWindowCreate, this, -1, (m, ScrolledWindowContainerSub, ScrolledWindowMain, ScrolledWindowSizer, initalWindowWidth);
Update:
So I found out that you need to store the arguments as wxClientData, I believe I've done so successfully but I still don't know how to extract the individual items from it.
struct CustomData final : public wxClientData {
int PanelNum = 20;
std::list<std::string> TagList{ "Paid", "Needs invoice" };
std::map<std::string, std::variant<std::string, std::list<std::string>>> m{ {"TIME","8:69"}, {"HEADER","Title"},{"TAGS", TagList},{"CONTENT", "Hey this is content!"} };
wxPanel* ScrolledWindowContainerSub;
wxPanel* ScrolledWindowMain;
wxBoxSizer* ScrolledWindowSizer;
int initalWindowWidth = 1300;
};
// Panels that are set as arguments below are defined here
// wxPanel* ScrolledWindowContainerSub = ...; etc...
CustomData* const myData{ new CustomData() };
myData->PanelNum, m, ScrolledWindowContainerSub, ScrolledWindowMain, ScrolledWindowSizer, initalWindowWidth;
ScrolledWindowContainerSub->SetClientObject(myData);
ScrolledWindowContainerSub->Bind(wxEVT_SCROLL_BOTTOM, &MyFrame::ScrolledWindowScrolled, this);
void MyFrame::ScrolledWindowScrolled(wxScrollEvent& event) {
wxObject* Obj = event.GetEventObject();
wxClientData* ObjClientData = static_cast<wxEvtHandler*>(Obj)->GetClientObject();
wxPanel* ObjStaticChild = dynamic_cast<wxPanel*>(ObjClientData); // Which panel will this give me? I've put two as parameters
};
| Bind() does support passing pointers to arbitrary "user data", but this is not the best way to do it and is only supported for backwards compatibility and to ease migration of the very old code predating Bind().
Instead, consider making the data you need part of some object -- typically something deriving from a window class and representing the window you're binding to, but not necessarily so -- and bind to a member function of this object, in which you will have access to all the data you need.
Remember that you don't need to bind to the object generating the event, or its parent. You can use anything you want, including a lambda, for example.
|
72,458,457 | 72,458,743 | This is a program to recursively calculate the reverse of a string but it's not printing anything | What I have done is created a global array to store the reversed string.
#include <bits/stdc++.h>
using namespace std;
char arr[10];
int c = 1;
string Reverser(string z)
{
arr[c] = z[(z.size() - c)];
c++;
if (c == (z.size() + 1))
{
return 0;
}
else
{
Reverser(z);
}
return 0;
}
int main()
{
string z;
cin >> z;
string Reverser(z);
for (int i = 1; i <= z.size(); i++)
{
cout << arr[i];
}
return 0;
}
I have also tried to dry run it but I can't really find any error.
| You can use a std::stringstream and pass it by reference in your recursive function. Also, you can pass the string by reference.
#include <iostream>
#include <string>
#include <sstream>
void reverse(const std::string& a, std::stringstream& ss, unsigned int pos)
{
ss << a[pos];
if (pos == 0) return;
reverse(a, ss, pos - 1);
}
void reverse(const std::string& a, std::stringstream& ss)
{
reverse(a, ss, a.length() - 1);
}
int main()
{
std::stringstream ss;
std::string input = "Hello";
reverse(input, ss);
std::cout << ss.str() << std::endl;
}
|
72,459,809 | 72,460,017 | Is false sharing the case with heap memory? | As I know, false sharing occurs when several threads try to read small and adjacent pieces of data which are placed within the same cache line:
#include <omp.h>
#define NUM_THREADS 4
int main() {
int arr[NUM_THREADS];
# pragma omp parallel num_threads(NUM_THREADS)
{
const int id = omp_get_thread_num();
arr[id] // doing something with it
}
}
What if I create the array dynamically?
int *arr = new int[NUM_THREADS];
Will false sharing take place if I have my array on the heap? Are there some cache line restrictions in this case?
| Memory is memory. To the cpu an array on the stack is exactly the same as an array on the heap. So any false sharing problem remains the same.
|
72,460,511 | 72,499,230 | Error while computing Surface Normal using Camera Intrinsic Matrix in OpenCV | I am trying to compute surface normals in OpenCV. Well, this should be quick and easy but I don't know why it is not working. Below is the code:
> import cv2
> img_color = cv2.imread("color.png")
> img_depth = cv2.imread("depth.png", cv2.CV_16UC1) # millimeters
> img_color.shape, img_color.dtype
((720, 1280, 3), dtype('uint8'))
> img_depth.shape, img_depth.dtype
((720, 1280), dtype('uint16'))
> k = np.array([[ fx, 0, cx ],
[ 0, fy, cy ],
[ 0, 0, 1 ]])
> k
array([[900, 0, 640],
[ 0, 900, 360],
[ 0, 0, 1]])
> img_depth_m = img_depth.astype('float32') * 0.001 # meter
> rows, cols = img_depth_m.shape
> normal_estimator = cv2.rgbd.RgbdNormals_create(rows, cols, cv2.CV_32F, k, 3)
> normals = normal_estimator.apply( img_depth_m )
It throws the following error:
error Traceback (most recent call last)
/tmp/ipykernel_19178/1208043521.py in <module>
----> 4 normals = normal_estimator.apply( img_depth_m )
error: OpenCV(4.2.0) ../contrib/modules/rgbd/src/normal.cpp:776:
error: (-215:Assertion failed) points3d_ori.channels() == 3 in function 'operator()'
It seems that OpenCV is expecting a 3 Channel input matrix. However, I looked at the docstring in the notebook, it says:
Docstring:
apply(points[, normals]) -> normals
. Given a set of 3d points in a depth image, compute the normals at each point.
. * @param points a rows x cols x 3 matrix of CV_32F/CV64F or a rows x cols x 1 CV_U16S
. * @param normals a rows x cols x 3 matrix
Type: builtin_function_or_method
Anyway, how to compute surface normals using camera intrinsic matrix in OpenCV?
PS: I am using OpenCV v4.2.0 on Ubuntu 20.04 LTS.
| There is a function called depthTo3d in OpenCV to do convert depth image into 3D points. Please see the following code snippet:
In [1]: import cv2
In [2]: cv2.rgbd.depthTo3d?
Docstring:
depthTo3d(depth, K[, points3d[, mask]]) -> points3d
. Converts a depth image to an organized set of 3d points.
. * The coordinate system is x pointing left, y down and z away from the camera
. * @param depth the depth image (if given as short int CV_U, it is assumed to be the depth in millimeters
. * (as done with the Microsoft Kinect), otherwise, if given as CV_32F or CV_64F, it is assumed in meters)
. * @param K The calibration matrix
. * @param points3d the resulting 3d points. They are of depth the same as `depth` if it is CV_32F or CV_64F, and the
. * depth of `K` if `depth` is of depth CV_U
. * @param mask the mask of the points to consider (can be empty)
Type: builtin_function_or_method
In [3]: points3d = cv2.rgbd.depthTo3d(img_depth, k)
In [4]: normal_estimator = cv2.rgbd.RgbdNormals_create(rows, cols, cv2.CV_32F, k, 3)
In [5]: normals = normal_estimator.apply( points3d )
|
72,460,975 | 72,461,759 | Assembly 32bits sum of elements of two vectors | I have a problem with sum of elements of two vectors type double which are the same size. Code always returns 0.
#include <iostream>
using namespace std;
int main()
{
int n = 5;
double* tab = new double[n];
double* tab3 = new double[n];
for (size_t i = 0; i < n; i++)
{
tab[i] = 1;
tab3[i] = 1;
}
double sum;
__asm {
mov eax, n; //vector size
mov edi, tab; //first vector
mov esi, tab3; //second vector
fldz;
l:
fadd[edi + 8 * eax - 8];
fadd[esi + 8 * eax - 8];
dec eax;
jnz l;
fstp sum;
}
cout << sum;
}
| Sadly i am not on windows, so i had to modify the code to use g++ instead of msvc, but i used intel syntax assembly too. During debugging it turned out that fadd instructions had no effect. I fixed it by adding qword ptr before the [edi + 8 * eax - 8] and [esi + 8 * eax - 8] to tell assembler to use pointers to an 8 byte value (since you are using double instead of float):
fadd qword ptr [edi + 8 * eax - 8];
fadd qword ptr [esi + 8 * eax - 8];
|
72,462,450 | 72,462,472 | Return lambda with capture from a function in c++11 | The standard 5.1.2 6 says that there is a conversion function from a lambda expression without capture to the corresponding function pointer type. What about lambdas with capture? The following code compiles without warnings. Does this lead to undefined behavior?
std::function<void()> makeFucntion(int& parameter)
{
return [¶meter]() // convert the lambda to std::function
{
cout << parameter;
};
}
int var = 4;
auto foo = makeFucntion(var);
foo();
And if there is undefined behavior, is there another way to return a lambda expression with a capture from a function in c++11?
| std::function<void()> is not a function pointer. std::function<void()> can store more than just function pointers.
If you'd try to return a function pointer void(*)() then the code would fail to compile, because lambdas with capture do not have a conversion to function pointer.
As parameter is passed and capture by referene and var is still in scope while you call foo() the code is fine.
|
72,462,468 | 72,462,509 | Does placement-new into the same type still require to manually call the destructor? | Context
I'm trying to get a grasp on the placement-new mechanism since I never have had to use it. I'm trying to understand how to properly use it out of pure curiosity.
For the question, we will consider the following code base for illustration purposes:
struct Pack
{
int a, b, c, d;
Pack() = default;
Pack(int w, int x, int y, int z) : a(w), b(x), c(y), d(z)
{}
~Pack()
{
std::cout << "Destroyed\n";
}
};
std::ostream & operator<<(std::ostream & os, const Pack & p)
{
os << '[' << p.a << ", " << p.b << ", " << p.c << ", " << p.d << ']';
return os;
}
Basically it just defines a structure holding some data (4 integers in the example), and I overloaded the operator<<() to simplify the code in the testing part.
I know that when using placement-new, one has to manually call the destructor of the object because we can't use delete since we only want to destroy the object (and not to free the memory since it was already allocated).
Example (A):
char b[sizeof(Pack)];
Pack * p = new (b) Pack(1, 2, 3, 4);
std::cout << *reinterpret_cast<Pack*>(b) << '\n';
p->~Pack();
Question
I was wondering, when using placement-new into an object of the same type, is it still necessary to call the destructor of the object ?
Example (B):
Pack p;
new (&p) Pack(1, 2, 3, 4);
std::cout << p << '\n';
I did a quick test of both version here and it seems that the destructor is properly called when the underlying object goes out of scope while being of type Pack.
I know it's stupid to use placement-new in such a trivial example instead of directly creating the object. But in a real-case example, it can be a buffer or Pack instead of a buffer of char.
I would like to know if I am right to assume that I don't need to manually call the destructor in the example (B) or if I'm missing something.
Extra
As a subsidiary question, in the example (A), is it legal to get rid of the returned pointer and call the destructor through the reinterpret_casted pointer instead ?
For example can it be rewritten like this:
char b[sizeof(Pack)];
new (b) Pack(1, 2, 3, 4);
std::cout << *reinterpret_cast<Pack*>(b) << '\n';
reinterpret_cast<Pack*>(b)->~Pack(); // Is it legal ?
It would be useful in the case I have a buffer of objects and I want to destroy its elements without having to keep the returned pointers somewhere.
[Disclaimer]: Of course, in a real case program, I would use a std::vector and the emplace_back() function instead of my own buffer. As already mentioned, this question is purely out of curiosity, just to understand how it's meant to work under the hood.
| Yes, you must call the destructor. It's irrelevant whether the old object is of same type or not.
Only thing that matters is whether the type of the old object is trivially destructible. If it is, then there is no need to call the destructor. If it isn't, then you must call the destructor before reusing the memory.
Example:
Pack p;
new (&p) Pack(1, 2, 3, 4); // Not OK
p.~Pack();
new (&p) Pack(1, 2, 3, 4); // OK
Note that there are cases where this isn't allowed such as if the class contains const qualified members or reference members. In general, I recommend avoiding such pattern, and to instead re-use only arrays of char or similar trivial storage.
As a subsidiary question, in the example (A), is it legal to get rid of the returned pointer and call the destructor through the reinterpret_casted pointer instead ?
Just like all uses of the placement-newed object, you can reintepret the addresss of the original object, but you must launder it:
Pack* ptr = new (b) Pack(1, 2, 3, 4);
std::cout << *ptr << '\n'; // OK
std::cout << *reinterpret_cast<Pack*>(b) << '\n'; // Not OK
std::cout << *std::launder(reinterpret_cast<Pack*>(b)) << '\n'; // OK
ptr->~Pack(); // OK
reinterpret_cast<Pack*>(b)->~Pack(); // Not OK
std::launder(reinterpret_cast<Pack*>(b))->~Pack(); // OK
char b[sizeof(Pack)];
Pack * p = new (b) Pack(1, 2, 3, 4);
This is wrong. You must ensure that the storage is properly aligned for the placement-newed type:
alignas(alignof(Pack)) char b[sizeof(Pack)];
|
72,462,807 | 72,463,536 | If arr[3] is an array and ptr is a pointer, then why do arr and &arr give same result but ptr and &ptr don't | I am a beginner to data structures and algorithms, started studying the pointers now and before asking the question here I read this recommended post but I couldn't understand it so I am asking the query here.
I have been told by a friend that array's name is a pointer to the first value in the array, as arr returns the address of arr[0], arr+1 returns address of arr[1], so when I write this
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i = 10;
int arr[3] = {1, 2, 3};
int *ptr = &i;
cout << arr << " " << &arr << endl;
cout << ptr << " " << &ptr;
return 0;
}
Both arr and &arr give same result
0x61ff00 0x61ff00
While ptr and &ptr give different results
0x61ff0c 0x61fefc
Can someone tell me why is this happening ?
| Arrays are not pointers!
Arrays do decay to a pointer to their first element in all sorts of circumstances. For example std::cout << arr; actually prints the memory address of the first element of the array. std::cout << &arr; prints the memory address of the array. As the address of the first element is the same as the address of the array you see the same value.
However, just because they have the same value, does not mean they are the same. arr can decay to a int*, while &arr is a pointer to an array, a int(*)[3].
I hope the following will help to clear things up a little:
#include <iostream>
#include <type_traits>
void make_it_decay(int x[]) {
std::cout << std::is_same_v< decltype(x), int*> << "\n";
}
int main() {
int arr[3] = {1,2,3};
//std::cout << (arr == &arr) << "\n"; // does not compile !
std::cout << (arr == &(arr[0])) << "\n";
std::cout << std::is_same_v< decltype(arr), int[3]> << "\n";
std::cout << std::is_same_v< decltype(&arr),int(*)[3]> << "\n";
std::cout << std::is_same_v< decltype(&arr[0]), int* > << "\n";
make_it_decay(arr);
}
output:
1
1
1
1
1
I use decltype to infer the type of certain expressions and std::is_same_v to see if the expressions are of same type.
arr is of type int[3]. It is an array. It is not a pointer.
&arr is the address of the array. It is a pointer to an array with three elements, a int(*)[3].
&arr[0] even though it has the same value as &arr is of different type. It is a pointer to int, an int*.
When we pass arr to a function then it decays to a pointer to the first element of the array. And we can see that inside the function x is int*.
Now to your quesiton...
Above I tried to lay out what happens when you write std::cout << arr. Pointers are different, because ... well arrays are not pointers.
std::cout << ptr; // prints the value ptr
std::cout << &ptr; // prints the address of ptr
Perhaps some visualization helps. The difference in types gets most apparent when incrementing the pointers
-------------------
| arr |
-------------------
| 1 | 2 | 3 |
-------------------
^ ^ ^
&arr | &arr + 1
&arr[0] |
&arr[0] + 1
|
72,462,904 | 72,463,449 | boost: parse json file and get a child | I am trying to pars a JSON file with the following function:
std::string getFieldFromJson_data(std::string json, std::string field)
{
std::stringstream jsonEncoded(json); // string to stream convertion
boost::property_tree::ptree root;
boost::property_tree::read_json(jsonEncoded, root);
if (root.empty())
return "";
return (root.get<std::string>(field));
}
It works when reading elements like
device_json.data_device_id = stoi(getFieldFromJson_data(output, "data.device_id"));
My JSON file looks similar to:
{
"data": {
"device_id": 67,
"place_open": {
"monday": [
"10:15","19:30"
]
}
}
}
I can read the value of "data.device_id", but when i try to read the value of "data.place_open.monday" I get an empty string.
| Use a JSON library. Property Tree is not a JSON library. Using Boost JSON and JSON Pointer:
Live On Coliru
#include <boost/json.hpp>
#include <boost/json/src.hpp> // for header-only
#include <iostream>
#include <string_view>
auto getField(std::string_view json, std::string_view field) {
return boost::json::parse(json).at_pointer(field);
}
int main() {
auto output = R"({
"data": {
"device_id": 67,
"place_open": {
"monday": ["10:15", "19:30"]
}
}
})";
for (auto pointer : {
"/data",
"/data/device_id",
"/data/place_open/monday",
"/data/place_open/monday/0",
"/data/place_open/monday/1",
})
std::cout << pointer << " -> " << getField(output, pointer) << std::endl;
}
Prints
/data -> {"device_id":67,"place_open":{"monday":["10:15","19:30"]}}
/data/device_id -> 67
/data/place_open/monday -> ["10:15","19:30"]
/data/place_open/monday/0 -> "10:15"
/data/place_open/monday/1 -> "19:30"
|
72,463,355 | 72,463,629 | What exactly is std::function<void(int)> doing in this code? | I've recently come across some code for the inorder traversal of a binary search tree which is as follows:
void binary_search_tree::inorder_traversal(bst_node *node, std::function<void(int)> callback) {
if (node == nullptr) {
return;
}
inorder_traversal(node->left, callback);
callback(node->value);
inorder_traversal(node->right, callback);
}
std::vector<int> binary_search_tree::get_elements_inorder() {
std::vector<int> elements;
inorder_traversal(root, [&](int node_value) {
elements.push_back(node_value);
});
return elements;
}
From my understanding, the first function recursively traverses the BST inorder, visiting the left, then the node, then the right. The second function then calls this function to add each element to the vector as each node is hit.
My confusion comes from how each value of the node is obtained. Does callback(node->value) store each node value somewhere to be used later? I'm not exactly sure about how this works.
Any help would be much appreciated :) Thank you!
| https://en.cppreference.com/w/cpp/utility/functional/function has a pretty good description:
Class template std::function is a general-purpose polymorphic function
wrapper. Instances of std::function can store, copy, and invoke any
CopyConstructible Callable target -- functions, lambda expressions,
bind expressions, or other function objects, as well as pointers to
member functions and pointers to data members.
std::function<void(int)> stores a function (or similar) that can be called with an int argument and which returns nothing. In particular you can store a lambda in it.
Here the inorder_traversal function is called with the lambda [&](int node_value) { elements.push_back(node_value); } as argument (under the name callback).
Then later when inorder_traversal calls callback(node->value); it effectively calls the code elements.push_back(node->value). Well not exactly, since this only works because the lambda has captured elements - without that the vector would not be accessible here. But to know more about how that works I suggest that you read up on lambdas - it is a bit beyond the scope of this question.
|
72,463,360 | 72,463,589 | std::strcpy and std::strcat with a std::string argument |
This is from C++ Primer 5th edition. What do they mean by "the size of largeStr". largeStr is an instance of std::string so they have dynamic sizes?
Also I don't think the code compiles:
#include <string>
#include <cstring>
int main()
{
std::string s("test");
const char ca1[] = "apple";
std::strcpy(s, ca1);
}
Am I missing something?
| strcpy and strcat only operate on C strings. The passage is confusing because it describes but does not explicitly show a manually-sized C string. In order for the second snippet to compile, largeStr must be a different variable from the one in the first snippet:
char largeStr[100];
// disastrous if we miscalculated the size of largeStr
strcpy(largeStr, ca1); // copies ca1 into largeStr
strcat(largeStr, " "); // adds a space at the end of largeStr
strcat(largeStr, ca2); // concatenates ca2 onto largeStr
As described in the second paragraph, largeStr here is an array. Arrays have fixed sizes decided at compile time, so we're forced to pick some arbitrary size like 100 that we expect to be large enough to hold the result. However, this approach is "fraught with potential for serious error" because strcpy and strcat don't enforce the size limit of 100.
Also I don't think the code compiles...
As above, change s to an array and it will compile.
#include <cstring>
int main()
{
char s[100] = "test";
const char ca1[] = "apple";
std::strcpy(s, ca1);
}
Notice that I didn't write char s[] = "test";. It's important to reserve extra space for "apple" since it's longer than "test".
|
72,463,846 | 72,486,802 | Argument of type "float" is incompatible with parameter of type "const void *" | I am trying to design a basic matrix class having data allocated in device. I am having some problems when inserting an element into the matrix given its row and col. This is my actual code:
template <typename CellType_>
class CUDAMatrix {
public:
using CellType = CellType_;
CUDAMatrix(size_t rows_, size_t cols_) {
_rows = 0;
_cols = 0;
resize(rows_, cols_);
}
~CUDAMatrix() {
cudaFree(_data);
}
inline size_t rows() const {
return _rows;
}
inline size_t cols() const {
return _cols;
}
inline void _init() {
_capacity = _rows * _cols;
CUDA_CHECK(cudaMalloc((void**) &_data, sizeof(CellType) * _capacity));
}
inline void resize(size_t rows_, size_t cols_) {
// if size is ok, do nothing
if (_rows == rows_ && _cols == cols_)
return;
_rows = rows_;
_cols = cols_;
if (rows_ * cols_ <= _capacity)
return;
cudaFree(_data);
_init();
}
inline void set(const size_t row, const size_t col, const CellType& val) {
if (row > _rows || col > _cols) {
throw std::out_of_range("[Matrix::at] index out of range");
}
CUDA_CHECK(cudaMemcpy(_data[row * _cols + col], &val, sizeof(CellType), cudaMemcpyHostToDevice));
}
inline void clear() {
cudaFree(_data);
_capacity = 0;
_cols = 0;
_rows = 0;
}
protected:
size_t _cols;
size_t _rows;
size_t _capacity;
CellType* _data;
};
int main() {
const size_t rows = 620;
const size_t cols = 480;
using MyMat = CUDAMatrix<float>;
MyMat mymat(rows, cols);
for (size_t r = 0; r < mymat.rows(); ++r) {
for (size_t c = 0; r < mymat.cols(); ++c) {
mymat.set(r, c, 1.f);
}
}
}
How I can take an element from host and copy it to device? I am getting the error argument of type "float" is incompatible with parameter of type "const void *". The error arise here when I call cudaMalloc.
| cudaMemcpy requires pointer as src and dst, _data[index] does not return a pointer. The right way should be:
cudaMemcpy(&_data[row * _cols + col], &val, sizeof(CellType), cudaMemcpyHostToDevice)
|
72,464,347 | 72,464,544 | Can you use a constructor as a UnaryOperator? | If I have a class with a unary constructor, can I somehow use that constructor as a UnaryOperator in an algorithm? i.e.:
#include <algorithm>
#include <vector>
class Thing
{
public:
Thing(int i)
: m_i(i)
{}
int i() {
return m_i;
};
private:
int m_i;
};
int main() {
std::vector<int> numbers{0,4,-13,99};
std::vector<Thing> things;
std::transform(numbers.begin(), numbers.end(), std::back_inserter(things), Thing);
}
the above code doesn't work, the code below works but I'm wondering if there's a better way:
#include <algorithm>
#include <vector>
class Thing
{
public:
Thing(int i)
: m_i(i)
{}
int i() {
return m_i;
};
private:
int m_i;
};
int main() {
std::vector<int> numbers{0,4,-13,99};
std::vector<Thing> things;
auto make_thing = [](auto&& i){return Thing(i);};
std::transform(numbers.begin(), numbers.end(), std::back_inserter(things), make_thing);
}
| For the first code sample just use a lambda:
std::transform(numbers.begin(), numbers.end(), std::back_inserter(things), [](int i){ return Thing(i);});
And this is the best way for what your code does. Everybody will understand it.
Constructor can't be used as an UnaryOperator, because it does not return a value.
|
72,464,511 | 72,466,730 | can anyone help me in this time exceeds error | ** Consider the following sequence:
7,77,777, 7777,...
Let T be the smallest element in this sequence that is divisible by 2003. How many digits does T have?**
enter code here
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int a=0;
int count =0;
for(int i=1;;i++);
{
a=a*10+7;
if (a%2003==0)
{
break;
}
else
{
count++;;
}
}
cout << count+1 ;
return 0;
}
| Everything in this problem is known at compile time. So lets let the compiler solve this:
#include <stdio.h>
#include <cstddef>
consteval std::size_t solve() {
int a=0;
std::size_t count = 0;
do {
a = (a*10 +7) % 2003;
++count;
} while (a != 0);
return count;
}
int main() {
printf("%zd\n", solve());
}
resulting in:
.LC0:
.string "%zd\n"
main:
sub rsp, 8
mov esi, 1001
mov edi, OFFSET FLAT:.LC0
xor eax, eax
call printf
xor eax, eax
add rsp, 8
ret
As may see this only calls printf with 1001 as argument.
|
72,464,565 | 72,534,332 | Directx 9 Rotate Textured Vertex | I used vertexes to draw textures and did not have a problem but now i am trying to rotate some textures and getting black screen.
This is my initial code to draw texture with vertex.
struct CUSTOM_VERTEX { FLOAT X, Y, Z, RHW, U, V; };
#define CUSTOM_FVF (D3DFVF_XYZRHW | D3DFVF_TEX1 )
CUSTOM_VERTEX vertices[4] =
{ //X, Y, Z, RHW, U, V
100.0f, 100.0f, 0.0f, 1.0f, 0.0f, 0.0f,
1000.0f, 100.0f, 0.0f, 1.0f, 1.0f, 0.0f,
100.0f, 750.0f, 0.0f, 1.0f, 0.0f, 1.0f,
1000.0f, 750.0f, 0.0f, 1.0f, 1.0f, 1.0f
};
LPDIRECT3DVERTEXBUFFER9 v_buffer = NULL;
d3d9device->CreateVertexBuffer(4 * sizeof(CUSTOM_VERTEX),
0,
CUSTOM_FVF,
D3DPOOL_MANAGED,
&v_buffer,
NULL);
VOID* pVoid;
v_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, vertices, sizeof(vertices));
v_buffer->Unlock();
d3d9device->SetFVF(CUSTOM_FVF);
d3d9device->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOM_VERTEX));
d3d9device->SetTexture(0, d3d9texture);
d3d9device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
I read that RHW describes pre-transformed vertices. Then i changed CUSTOM_VERTEX, CUSTOM_FVF and added SetTransform.
struct CUSTOM_VERTEX { FLOAT X, Y, Z, U, V; };
#define CUSTOM_FVF (D3DFVF_XYZ | D3DFVF_TEX1 )
CUSTOM_VERTEX vertices[4] =
{ //X, Y, Z, U, V
100.0f, 100.0f, 0.0f, 0.0f, 0.0f,
1000.0f, 100.0f, 0.0f, 1.0f, 0.0f,
100.0f, 750.0f, 0.0f, 0.0f, 1.0f,
1000.0f, 750.0f, 0.0f, 1.0f, 1.0f
};
//CreateVertexBuffer, memcpy, SetFVF and SetStreamsource are the same as above
D3DXMATRIX worldMatrix;
D3DXMatrixRotationZ(&worldMatrix, D3DXToRadian(90));
d3d9device->SetTransform(D3DTS_WORLD, &worldMatrix);
//SetTexture and DrawPrimitive are the same as above
I also tried adding view and projection matrix.
D3DXMATRIX viewMatrix;
D3DXMatrixLookAtLH(&viewMatrix,
&D3DXVECTOR3 (0.0f, 0.0f, 10.0f),
&D3DXVECTOR3 (0.0f, 0.0f, 0.0f),
&D3DXVECTOR3 (0.0f, 1.0f, 0.0f));
d3d9device->SetTransform(D3DTS_VIEW, &viewMatrix);
D3DXMATRIX projectionMatrix;
D3DXMatrixPerspectiveFovLH(&projectionMatrix,
D3DXToRadian(45),
width / height,
1.0f,
1000.0f);
d3d9device->SetTransform(D3DTS_PROJECTION, &projectionMatrix);
I changed pEye and pAt inputs of D3DXMatrixLookAtLH method to center of vertex but again black screen.
| My problem was using the same points for both pre-transformed (RHW) and non pre-transformed vertices.
Solved problem like below.
struct CUSTOM_VERTEX { FLOAT X, Y, Z, U, V; };
#define CUSTOM_FVF (D3DFVF_XYZ | D3DFVF_TEX1 )
float halfBackBufferWidth = backBufferWidth / 2.0f;
float halfBackBufferHeight = backBufferHeight / 2.0f;
CUSTOM_VERTEX vertices[4] =
{ //X, Y, Z, U, V
{ halfBackBufferWidth - 100.0f, halfBackBufferHeight - 100.0f, 0.0f, 0.0f, 0.0f },
{ halfBackBufferWidth - 1000.0f, halfBackBufferHeight - 100.0f, 0.0f, 1.0f, 0.0f },
{ halfBackBufferWidth - 100.0f, halfBackBufferHeight - 750.0f, 0.0f, 0.0f, 1.0f },
{ halfBackBufferWidth - 1000.0f, halfBackBufferHeight - 750.0f, 0.0f, 1.0f, 1.0f }
};
LPDIRECT3DVERTEXBUFFER9 v_buffer = NULL;
d3d9device->CreateVertexBuffer(4 * sizeof(CUSTOM_VERTEX),
0,
CUSTOM_FVF,
D3DPOOL_MANAGED,
&v_buffer,
NULL);
VOID* pVoid;
v_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, vertices, sizeof(vertices));
v_buffer->Unlock();
d3d9device->SetFVF(CUSTOM_FVF);
d3d9device->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOM_VERTEX));
D3DXMATRIX worldMatrix;
D3DXMatrixRotationZ(&worldMatrix, D3DXToRadian(45));
d3d9device->SetTransform(D3DTS_WORLD, &worldMatrix);
D3DXMATRIX viewMatrix;
D3DXMatrixLookAtLH(&viewMatrix,
&D3DXVECTOR3 (0.0f, 0.0f, halfBackBufferHeight),
&D3DXVECTOR3 (0.0f, 0.0f, 0.0f),
&D3DXVECTOR3 (0.0f, 1.0f, 0.0f));
d3d9device->SetTransform(D3DTS_VIEW, &viewMatrix);
D3DXMATRIX projectionMatrix;
D3DXMatrixPerspectiveFovLH(&projectionMatrix,
D3DXToRadian(90),
backBufferWidth / backBufferHeight,
1.0f,
halfBackBufferHeight);
d3d9device->SetTransform(D3DTS_PROJECTION, &projectionMatrix);
d3d9device->SetTexture(0, d3d9texture);
d3d9device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
I dont want to add light so I disable it. If I dont disable it, I get black screen.
d3d9device->SetRenderState(D3DRS_LIGHTING, FALSE);
|
72,464,693 | 72,464,722 | How to disable mutex if called within another function locking same mutex | I've got a resource class being guarded by a std::mutex, where any methods accessing it must be locked and only executed by a single thread. This works fine if individual methods are called separately, but now I've got a requirement for batching those methods together. In this case, the mutex needs to be locked only once and those methods must not lock that mutex again(otherwise will end up in deadlock).
class Resource {
mutable std::mutex mtx;
int value = 10;
void handleOpStart() const {/* Activate batch mode */ std::cout << "HandleOp activate!"<< std::endl; }
void handleOpEnd() const {/* Deactivate batch mode */ std::cout << "HandleOp deactivate!"<< std::endl; }
public:
int read() const {
std::lock_guard<std::mutex> lock(mtx);
handleOpStart(); auto result = value + 10; handleOpEnd();
return result;
}
void write(int val) {
std::lock_guard<std::mutex> lock(mtx);
handleOpStart(); value = val; handleOpEnd();
}
template<typename Fn>
void batch(Fn fn) {
std::lock_guard<std::mutex> lock(mtx);
handleOpStart();
fn();
handleOpEnd();
}
void print() const {
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Value: " << value << std::endl;
}
};
int main() {
Resource r;
r.print();
r.write(r.read());
r.print();
r.batch([&] {
// will cause deadlock
auto someVal = r.read();
auto someOtherVal = 10 + someVal;
r.write(r.read() + someOtherVal);
});
}
Now I can't remove mutex from individual methods because they can be called separately from outside batch context. I can't keep the mutex because they can also be called inside it. If I keep a boolean variable inside class that deactivates mutex on the batch function call, then it also deactivates the other individual functions being called from other threads, defeating the purpose again.
One solution would be to write down a non-mutex set of all the read/write functions and only call them within batch context, not outside. But the number of such resources accessing functions is large, thus increasing maintenance and might introduce bugs.
Looking for alternatives to solve this problem.
| This is exactly what std::recursive_mutex is for, it can be locked multiple times from the same thread. It will only fully unlock when the number of unlock calls matches the number of lock calls.
|
72,464,958 | 72,465,902 | How to set a conditional breakpoint for C++ strings in VS2019? | I'm trying to set a conditional breakpoint for my debug but VS keeps returning me this error:
How can it be so if the operator != is defined for strings?
The variable error is std::string
| There are many workarounds you can do, for example a much better way of writing your condition is this:
!errors.empty()
You also have size() that you can compare against 0, c_str() that returns a C string which you can test the first element against \0, etc etc.
As to the reason why your line doesn't work is that most likely the conditional debugger can't resolve the overloaded operator. Perhaps checking against a non-implicitly built string (ie, error != string{}) would work better, or using a newer VS version, but really you can see how wasteful that is instead of just simply checking the empty() function result.
|
72,465,396 | 72,465,465 | std::vector<std::vector<float>> in header file throws error LNK1120 | I want to include my own header file but vector< vector < float > > throws an error
matrix.cpp
#include <vector>
class Matrix
{
public:
std::vector<std::vector<float>> data;
Matrix(std::vector<std::vector<float>> d_data = { {} })
{
data = d_data;
}
};
matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
class Matrix {
public:
std::vector<std::vector<float>> data;
Matrix(std::vector<std::vector<float>> d_data = { {} });
};
#endif
matrixc++.cpp
#include <C:\Users\Matteo\source\repos\matrixc++\matrixc++\Matrix.h>
#include <vector>
int main()
{
Matrix abc({{1,2},{2,1}});
return 0;
}
Following error occurs :
matrixc++.obj : error LNK2019: unresolved external symbol "public: __cdecl Matrix::Matrix(class std::vector<class std::vector<float,class std::allocator >,class std::allocator<class std::vector<float,class std::allocator > > >)" (??0Matrix@@QEAA@V?$vector@V?$vector@MV?$allocator@M@std@@@std@@V?$allocator@V?$vector@MV?$allocator@M@std@@@std@@@2@@std@@@Z) referenced in function main
| The problem is that you've more or less copy pasted the class definition to the source file matrix.cpp. That is, you have defined the class Matrix twice. Once in the header and second time in the source file.
To solve this just provide the implementation for the constructor Matrix::Matrix(std::vector<std::vector<float>>) inside the source file as shown below:
matrix.cpp
#include <C:\Users\Matteo\source\repos\matrixc++\matrixc++\Matrix.h>
//implement only the constructor
Matrix::Matrix(std::vector<std::vector<float>> d_data): data(d_data)
^^^^^^^^^^^^ use constructor initializer list
{
}
matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
class Matrix {
public:
std::vector<std::vector<float>> data;
Matrix(std::vector<std::vector<float>> d_data = { {} });
};
#endif
Working demo
|
72,465,968 | 72,466,036 | How to sort an vector based on any column value by passing the column index as input? | I have already tried the below code but i want to use this same function for sorting based on different columns.
This given code is sorting based on first column only.
bool sortcol( const vector <int> v1, const vector <int> v2)
{
return v1[0]<v2[0];
}
sort(ArrOfTimings.begin(), ArrOfTimings.end(), sortcol);
Is there any way possible to not make multiple functions but making it all work with one only.
Something like this
bool sortcol(int ind, const vector <int> v1, const vector <int> v2)
{
return v1[ind]<v2[ind];
}
sort(ArrOfTimings.begin(), ArrOfTimings.end(), sortcol(0));
| You cannot pass additional info to a free function used for comparison for std::sort by means other than global data.
You can create a struct with a member variable storing the column to compare in addition to providing a call operator for comparing the values though.
I'd prefer a lambda, since it results in shorter code though: Simply capture the index.
Note: It's also beneficial to avoid copying the vector by using references as parameters.
void SortByColumn(std::vector<std::vector<int>> & data, size_t column)
{
std::sort(data.begin(), data.end(),
[column](std::vector<int> const& v1, std::vector<int> const& v2)
{
return v1[column] < v2[column];
});
}
|
72,466,034 | 72,466,102 | to find number to be prime in c++ I'm getting numbers like 9 and 15 also prime . pls find the error in the code | I'm getting numbers like 9 and 15 also prime by using this code . pls find the error in the code and if possible Pls edit my code to find the error
Here is the code--
`#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the number : ";
cin>>n;
int flag=0;
//to check prime check from 2 to n
for(int i=2;i<=n;i++)
{
if(n%2==0)
{
cout<<n<<" is a non-prime number";
flag++;
break;
}
else
{
if(flag==0)
{
cout<<n<<" is a prime number";
break;
}
}
}
return 0;
}
| Your check logic is flawed as you are checking against %2, you should check against %i. I've also added a little optimization as you only need to check up until n/2.
To check if a number is prime:
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the number : ";
cin>>n;
bool prime=true;
//to check prime check from 2 to n
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
prime = false;
break;
}
}
if (prime)
cout<<n<<" is a prime number";
else
cout<<n<<" is a non-prime number";
return 0;
}
|
72,466,463 | 72,467,761 | Is alias construction of shared_ptr from void safe? | This is an entirely hypothetical question about shared_ptr aliasing constructor and UB.
Lets imagine a situation where we store std::shared_ptr<void> in some database. Lets also imagine that we can safely cast a void * pointing to an instance of a parent type A to a pointer of a child type B (ex. via a compile-time generated proxy).
Will the following situation result in UB, or is it safe?
std::shared_ptr<void> sp_v = get_vp(); // sp_v points to an instance of parent type `A`
B *ptr_b = cast_to_b(sp_v.get()); // Safe cast of `void *` aliasing `A *` to `B *` via a proxy.
std::shared_ptr<B> sp_b = std::shared_ptr<B>{sp_v, ptr_b}; // <- Potential UB here?
From what i assume, there should be no UB, as aliasing constructor should only share the control block, however i am not sure if there are any implementation-defined edge cases or STL definition quirks here that might result in UB.
| From https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr:
... such as in the typical use cases where ptr is a member of the object managed by r or is an alias (e.g., downcast) of r.get() ...
So this is exactly the envisioned use case.
|
72,467,023 | 72,467,374 | Program slower with multi-threads | I started learning programming with multi-threads and i have program. My program is slower with multi-threads:
multi-threads: ~ 8.5 sec
without multi-threads: ~ 4.96
Someone can explain me what is wrong with my code?
#include <iostream>
#include <thread>
#include <ctime>
using namespace std;
long long even_sum = 0;
long long odd_sum = 0;
void findEvenNumber(int start, int end){
for(int i=start;i<end;i++){
if(i%2==0){
even_sum++;
}
}
}
void findOddNumber(int start, int end){
for(int i=start;i<end;i++){
if(i%2==1){
odd_sum++;
}
}
}
void multiTask(){
thread t1(findEvenNumber,1,1000000000);
thread t2(findOddNumber,1,1000000000);
t1.join();
t2.join();
}
void noMultiTask(){
findEvenNumber(1,1000000000);
findOddNumber(1,1000000000);
}
int main(){
clock_t start = clock();
//noMultiTask();
//multiTask();
clock_t end = clock();
cout<<(double)(end - start)/CLOCKS_PER_SEC<<endl;
cout<<even_sum<<" "<<odd_sum<<endl;
return 0;
}
| At minimum, you have a false sharing problem. even_count and odd_count are almost certainly on the same cache line, which means when you want to touch one variable you're actually forcing the other thread to have its cacheline invalidated. There's more to false sharing than this, but for a quick overview there's a great talk by Scott Meyers that hits on it at the start: https://www.youtube.com/watch?v=WDIkqP4JbkE
By using local variables for odd/even count and only updating the globals at the end of the thread, I get much better performance on my system (1.23299 seconds vs 1.07338).
void findEvenNumber(int start, int end){
auto count = 0;
for(int i=start;i<end;i++){
if(i%2==0){
count++;
}
}
even_sum += count;
}
void findOddNumber(int start, int end){
auto count = 0;
for(int i=start;i<end;i++){
if(i%2==1){
count++;
}
}
odd_sum += count;
|
72,467,305 | 72,467,376 | Array printing out -858993460 | I've been trying to work out why my array is printing out -858993460 with the following code
int myInt = 0;
int myArray[10]; // I know this is undefined, but the same results occur if I put {} to initialize it
while(myInt <= 10)
{
myArray[myInt] = myInt;
myInt++;
std::cout << "Test " << myArray[myInt] << std::endl;
std::cout << "Counter " << myInt << std::endl;
}
When print this out, myInt increments fine. However, myArray is printing out -858993460. If I insert a break point and step over the while loop with each iteration, I can see the numbers are being fed into the array, but it only prints out that random number (assuming it's a random number from the stack/heap?).
Now, if I swap around the while loop so it's now
while(myInt <= 10)
{
myInt++;
myArray[myInt] = myInt;
}
it prints out the numbers correctly. I can't seem to work out what's going on here...
| Arrays in C (and by extension C++) are zero based, so an array of ten elements is indexed 0 through 9.
But your loop is trying to access elements 0 through 10. myArray[10] is actually the eleventh element of the array, which doesn't actually exist. Trying to change it is undefined behavior. Your original code was actually closer to being correct; your revised version only made it worse. What you want is:
int myInt = 0;
int myArray[10];
while(myInt < 10) // <- strictly LESS THAN
{
myArray[myInt] = myInt;
++myInt; // <- increment AFTER accessing/assigning
}
In comments, you added an additional requirement that myArray[0] should contain 1 and so forth. To get this, you need to access the element before modifying the index. You could do this with two variables:
int myInt = 0;
int myArray[10];
while(myInt < 10)
{
myArray[myInt] = myInt+1;
++myInt;
}
You can't combine the two, unfortunately:
int myInt = 0;
int myArray[10];
while(myInt < 10)
{
myArray[myInt] = ++myInt; // <- NOPE: wrong order
}
In the revised code where you try to print out the values, you tried to access myArray[MyInt] after you changed MyInt. So you're now looking at a different element than the one you just set. No surprise it didn't print out what you want! Just move the increment to the end:
while(myInt <= 10)
{
myArray[myInt] = myInt+1;
std::cout << "myArray [" << myInt << "] = " << myArray[myInt] << '\n';
++myInt; <- ALWAYS INCREMENT THE LOOP INDEX LAST
}
|
72,467,333 | 72,467,811 | C++17: Deducing function noexcept specifier as non-type parameter | I've noticed that MSVC sometimes fails to deduce non-type parameters that other compilers accept, and recently came upon a simple example involving the function noexcept specifier (which is part of the function's signature since C++17):
template <typename T> struct is_nocv_method : public std::false_type { };
template <typename ReturnT, typename ClassT, bool IsNoexcept, typename... Args>
struct is_nocv_method<ReturnT (ClassT::*)(Args...) noexcept(IsNoexcept)> : std::true_type { };
Godbolt suggests gcc 12.1 and clang 14.0 accept this without issue, but MSVC 14.31 (cl.exe 19.31) fails to compile, claiming IsNoexcept cannot be deduced. Is this a compiler defect?
Demo
| A non-type template parameter cannot be deduced from a noexcept-specifier.
[temp.deduct.type]/8 gives the list of contexts from which template parameters can be deduced. Essentially, it can be read as a list of ways to "unwrap" the argument type, and a list of positions in the unwrapped type from which template arguments can be deduced.
For example, the item T (T::*)(T) implies that if the parameter type and the argument type are both pointers to member functions, then template parameters can be deduced from the return type, the class type, and any argument types (for the member function), should they appear there.
You'll notice that there is no item of the form T() noexcept(i), T(T) noexcept(i), and so on.
Yet, some compilers choose to allow this kind of deduction anyway, probably because it is convenient. I would support adding it to the standard.
Edit (Oct 20, 2022): It appears that this will be changing in C++23: i will be deducible from noexcept(i). According to the issues list, this has "DR" status, which means it's retroactive (presumably to C++17).
|
72,467,734 | 72,468,069 | regex with string_view returns garbage | Matching a regex on a std::string_view works fine. But when I return matched substrings, they die for some reason. std::string_view argument is being destroyed upon the end of the function's scope, but the memory it points to is valid.
I expected std::match_results to point to the initial array and not to make any copies, but the behavior I observe shows that I am wrong.
Is it possible to make this function work without additional allocations for substrings?
#include <tuple>
#include <regex>
#include <string_view>
#include <iostream>
using configuration_str = std::string_view;
using platform_str = std::string_view;
std::tuple<configuration_str, platform_str> parse_condition_str(std::string_view conditionValue)
{
// TODO: fix regex
constexpr const auto ®exStr =
R"((?:\'\$\(Configuration\)\s*\|\s*\$\(Platform\)\s*\'==\'\s*)(.+)\|(.+)')";
static std::regex regex{ regexStr };
std::match_results<typename decltype(conditionValue)::const_iterator> matchResults{};
bool matched =
std::regex_match(conditionValue.cbegin(), conditionValue.cend(), matchResults, regex);
(void)matched;
std::string_view config = matchResults[1].str();
std::string_view platform = matchResults[2].str();
return { config, platform };
}
int main()
{
const auto &stringLiteralThatIsALIVE = "'$(Configuration)|$(Platform)'=='Release|x64'";
const auto&[config, platform] = parse_condition_str(stringLiteralThatIsALIVE);
std::cout << "config: " << config << "\nplatform: " << platform << std::endl;
return 0;
}
https://godbolt.org/z/TeYMnn56z
CLang-tydy shows a warning: Object backing the pointer will be destroyed at the end of the full expression
std::string_view platform = matchResults[2].str();
| For example, let's look at the following line:
std::string_view config = matchResults[1].str();
Here, matchResults is of type std::match_results, and [1] is its std::match_results::operator[], which returns an std::sub_match.
But then, .str() is its std::sub_match::str(), which returns an std::basic_string.
This returned temporary sting object will be destroyed at the end of the full-expression (thanks, @BenVoigt, for the correction), i.e., in this case, immediately after the config gets initialized and the line in question finishes executing. So, the Clang's warning you quote is correct.
By the time when the parse_condition_str() function returns, both the config and platform string-views will thus be pointing into already destroyed strings.
|
72,467,966 | 72,478,370 | How can I split a raw buffer of uint8 I420 video data into YUV pointers? | I have a raw uint8 pointer to a buffer containing I420 formatted video data, and a buffer size. I also know the frame width / height. I want to feed the data into a library which can create video frames via this function signature:
Copy(int width, int height,
const uint8_t* data_y, int stride_y,
const uint8_t* data_u, int stride_u,
const uint8_t* data_v, int stride_v)
Is there some simple pointer arithmetic to resolve this?
| The best site I know for describing the various YUV and RGB video formats is FOURCC - the YUV descriptions are here.
The I420 format you refer to is described here. That means that your raw data will be organised like this:
Y plane, of H x W bytes, with a line stride of W bytes
U plane, of H/2 x W/2 bytes, with a line stride of W/2 bytes
V plane, of H/2 x W/2 bytes, with a line stride of W/2 bytes
I find ffmpeg is the very best tool for generating YUV data to encode into and decode out of your own software. Here are some tips for working with ffmpeg and raw YUV.
You can get a list of the pixel formats it supports with:
ffmpeg -pix_fmts
So, to find yours, I looked for something with 420 in it:
ffmpeg -pix_fmts | grep 420p
IO... yuv420p 3 12 8-8-8
so I know I need -pix_fmt yuv420p to encode or decode your data. I can also get a decent description of how that is laid out by checking the ffmpeg source here. The 12 above means 12 bits per pixel.
Then I wanted to:
generate a sample I420 frame with ffmpeg
split it apart with dd and extract the Y, U and V channels with IMageMagick
recombine the Y, U and V channels with ImageMagick
recombine the Y, U and V channels with ffmpeg
so I made the following bash script:
#!/bin/bash
################################################################################
# User-editable values
################################################################################
# Define WIDTH and HEIGHT of the frame we want to generate...
# ... so we are consistent all the way through
W=640
H=480
PIX_FMT="yuv420p"
################################################################################
# Derived values - do not edit
################################################################################
BASENAME="${PIX_FMT}-${W}x${H}"
FILENAME="${BASENAME}.raw"
PNGNAME="${BASENAME}.png"
UVW=$((W/2)) # width of U plane, same as V plane
UVH=$((H/2)) # height of U plane, same as V plane
YBYTES=$((H*W)) # bytes in Y plane
UBYTES=$((UVW*UVH)) # bytes in U plane, same as in V plane
# Generate a sample frame
echo "Generating sample: ${FILENAME}, and viewable PNG equivalent: ${PNGNAME}"
ffmpeg -y -f lavfi -i testsrc=size=${W}x${H}:rate=1:duration=1 -vcodec rawvideo -pix_fmt "$PIX_FMT" -f image2pipe - > "$FILENAME"
ffmpeg -y -f lavfi -i testsrc=size=${W}x${H}:rate=1:duration=1 "$PNGNAME"
# Check its size in bytes
ls -l "$FILENAME"
# Extract Y plane from sample into "Y.png" using ImageMagick
echo "Extracting Y plane into Y.png"
dd if="$FILENAME" bs=$YBYTES count=1 | magick -depth 8 -size ${W}x${H} gray:- Y.png
# Extract U plane from sample into "U.png" using ImageMagick
echo "Extracting U plane into U.png"
dd if="$FILENAME" bs=1 skip=$YBYTES count=$UBYTES | magick -depth 8 -size ${UVW}x${UVH} gray:- U.png
# Extract V plane from sample into "V.png" using ImageMagick
echo "Extracting V plane into V.png"
dd if="$FILENAME" bs=1 skip=$((YBYTES+UBYTES)) count=$UBYTES | magick -depth 8 -size ${UVW}x${UVH} gray:- V.png
# Recombine with ImageMagick
echo "Combining Y.png, U.png, V.png into result.png"
magick Y.png \( U.png v.png -resize 200% \) -set colorspace YUV -combine result.png
# Create a PNG from the YUV420p raw data just the same with 'ffmpeg'
echo "Create PNG from the YUV420p raw data as 'extracted.png'"
ffmpeg -y -f rawvideo -video_size 640x480 -pixel_format yuv420p -i - extracted.png < "$FILENAME"
That creates this image as PNG and as I420 data for you to test with:
and these Y, U and V planes:
|
72,467,979 | 72,468,016 | Where does C++20 prohibit sizeof...T (without parentheses) | Both g++ and clang++ reject the use of sizeof... when the argument is not parenthesized. For example, the following code is rejected:
template<typename... T> auto packsize = sizeof...T;
$ g++ -std=c++20 -ggdb -O -Wall -Werror -c -o z.o z.cc
z.cc:1:50: error: 'sizeof...' argument must be surrounded by parentheses [-fpermissive]
1 | template<typename... T> auto packsize = sizeof...T;
| ^
$ clang++ -std=c++20 -ggdb -O -Wall -Werror -c -o z.o z.cc
z.cc:1:50: error: missing parentheses around the size of parameter pack 'T'
template<typename... T> auto packsize = sizeof...T;
^
()
1 error generated.
CPPreference.org also seems to require parentheses around T. However, such a restriction does not appear in any of the obvious places in the C++20 standard, e.g., the discussion of sizeof... or the discussion of pack expansions. However, all non-normative examples in the standard do include parentheses.
My question: what normative language prohibits the use of sizeof... with an unparenthesized identifier in C++20?
| It's required by the grammar:
[expr.unary.general]/1
unary-expression:
...
sizeof ... ( identifier )
...
|
72,468,086 | 72,468,414 | While Loop vs Do While Loop | I am working on a program in C++ for my class to prepend, append, insert, display items of a circular-list. I came across while loop functioning differently then a do-while loop for what to my mind would potentially output the same items. I am looking for an explanation to why the output is different with the code blocks below, thank you. If you have places were I can modify code to enhance it please let me know trying to build as much information as possible again Thank You.
Link to full code: Pastebin
while(temp != head)
{
cout << temp->data << " ";
temp = temp->next;
}
Output: Nothing
do
{
cout << temp->data << " ";
temp = temp->next;
}while(temp != head);
Output: 10 20
| A while loop evaluates its condition before entering the body. So, a while loop may run 0 iterations.
A do..while loop evaluates its condition after leaving the body. So, a do..while loop will always run at least 1 iteration.
Using a while loop will not work in this situation, since the condition (temp != head) will always be false before the 1st iteration. If the list is empty, head will be NULL, so temp will then be set to NULL, thus (NULL != NULL) will be false. Otherwise, head will not be NULL, and temp will be set to point at the same Node that head is pointing at, thus (temp != head) will still be false.
Whereas, using a do..while loop instead, the condition (temp != head) will be false only after the last Node in the list has been iterated.
So, using a do..while loop is the way to go in this situation.
However, your code is not accounting for the possibility of an empty list (head is NULL), so you need to add that check to avoid dereferencing a NULL pointer, eg:
void displayData()
{
if (head) // <-- add this!
{
Node* temp = head;
do
{
cout << temp->data << " ";
temp = temp->next;
}
while (temp != head);
}
}
Online Demo
Also, your appendNode() can be simplified:
void appendNode(int newVal)
{
Node** temp = &head;
if (head) {
do {
temp = &((*temp)->next);
}
while (*temp != head);
}
*temp = new Node;
(*temp)->data = newVal;
(*temp)->next = head;
}
Online Demo
|
72,469,399 | 72,469,475 | Directly creating an object in a function call | Suppose a function Foo() takes an object of type Bar.
Instead of
Bar bar(parameters);
Foo(bar);
You can do Foo(Bar(parameters);
Why isn't the second case allowed when Foo is defined to take a reference i.e returntype Foo(Bar &bar);
| An lvalue reference (the kind you're referring to, written as T&) refers to an lvalue. Now the exact details of what that means are kind of complicated in modern C++, but the basic idea is that an lvalue is a thing that you can assign to. The name originally comes from the fact that an lvalue (where "l" is short for "left") can appear on the left-hand side of an assignment statement.
Non-const variables with names can be assigned to, naturally, so they can be passed as lvalue references. But temporaries are, generally speaking, not lvalues, since they don't refer to a place that can be assigned to.
If your function isn't going to modify the argument, you can take a const T&, a constant lvalue reference. This is very common in constructors, especially if the constructor is just going to copy the data out into its own storage anyway. If you are planning to modify the argument, then read on.
References in C++ (before C++11) sort of served double duty. They were meant as "I can assign to this position" and also as "this is a pointer-like thing that I'm borrowing and I won't modify". The second meaning was mostly captured by const T&, constant lvalue references. But there was still one case where we needed more. Specifically, if I had a value that I was never going to use again (such as, but not necessarily, a temporary value), then I might want to pass it by (mutable) reference to a function so that function can destructure it and potentially reuse parts of it.
A prime example of this is an array-like container. Say I've got an array class, say Vector, that consists of a pointer to some data and a size variable. If I need to make a copy of that variable, then in principle I need to copy the whole array. But if I know I'll never use the original vector again, I can instead move the vector, simply assigning the pointer and size variables directly and avoiding the need for a messy O(n) copy. But to do this, I would need exactly what you're describing. I would need a mutable pointer type that can take rvalues, or things that can't appear on the left-hand side of an assignment statement.
Enter rvalue references, which are written T&&. These are like lvalue references except that they can take temporary locations. An rvalue reference can still modify its argument but understands that its argument is, in principle, not going to be around much longer. So you shouldn't store the address of that thing in a class, because it's not going to live much longer, but you can still do things with it, most prominently move data out of it.
Long story short, if you don't want to modify the argument, then you should write your function as
void Foo(const Bar& arg)
If you need to modify the argument, but you understand fully that the memory might not be around for much longer, then you can use an rvalue reference.
void Foo(Bar&& arg)
|
72,469,687 | 72,469,739 | Why does this bad universal initializer syntax compile and result in unpredictable behavior? | I have a bunch of code for working with hardware (FPGA) registers, which is roughly of the form:
struct SomeRegFields {
unsigned int lower : 16;
unsigned int upper : 16;
};
union SomeReg {
uint32_t wholeReg;
SomeRegFields fields;
};
(Most of these register types are more complex. This is illustrative.)
While cleaning up a bunch of code that set up registers in the following way:
SomeReg reg1;
reg1.wholeReg = 0;
// ... assign individual fields
card->writeReg(REG1_ADDRESS, reg1.wholeReg);
SomeReg reg2;
reg2.wholeReg = card->readReg(REG2_ADDRESS);
// ... do something with reg2 field values
I got a bit absent-minded and accidentally ended up with the following:
SomeReg reg1{ reg1.wholeReg = 0 };
SomeReg reg2{ reg2.wholeReg = card->readReg(REG2_ADDRESS) };
The reg1.wholeReg = part is wrong, of course, and should be removed.
What's bugging me is that this compiles on both MSVC and GCC. I would have expected a syntax error here. Moreover, sometimes it works fine and the value actually gets copied/assigned correctly, but other times, it will result in a 0 value even if the register value returned is non-0. It's unpredictable, but appears to be consistent between runs which cases work and which don't.
Any idea why the compilers don't flag this as bad syntax, and why it seems to work in some cases but breaks in others? I assume this is undefined behavior, of course, but why would it would change behaviors between what often seem like nearly identical calls, often back-to-back?
Some compilation info:
If I run this through Compiler Explorer:
int main()
{
SomeReg myReg { myReg.wholeReg = 10 };
return myReg.fields.upper;
}
This is the code GCC trunk spits out for main with optimization off (-O0):
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 10
* mov eax, DWORD PTR [rbp-4]
* mov DWORD PTR [rbp-4], eax
movzx eax, WORD PTR [rbp-2]
movzx eax, ax
pop rbp
ret
The lines marked with * are the only difference between this version and a version without the bad myReg.wholeReg = part. MSVC gives similar results, though even with optimization off, it seems to be doing some. In this case, it just causes an extra assignment in and back out of a register, so it still works as intended, but given my accidental experimental results, it must not always compile this way in more complex cases, i.e. not assigning from a compile-time-deducible value.
| reg1.wholeReg = card->readReg(REG2_ADDRESS)
This is simply treated as an expression. You are assigning the return value of card->readReg(REG2_ADDRESS) to reg1.wholeReg and then you use the result of this expression (a lvalue referring to reg1.wholeReg) to aggregate-initialize the first member of reg2 (i.e. reg2.wholeReg). Afterwards reg1 and reg2 should hold the same value, the return value of the function.
Syntactically the same happens in
SomeReg reg1{ reg1.wholeReg = 0 };
However, here it is technically undefined behavior since you are not allowed to access variables or class members before they are initialized. Practically speaking, I would expect this to usually work nontheless, initializing reg1.wholeReg to 0 and then once again.
Referring to a variable in its own initializer is syntactically correct and may sometimes be useful (e.g. to pass a pointer to the variable itself). This is why there is no compilation error.
int main()
{
SomeReg myReg { myReg.wholeReg = 10 };
return myReg.fields.upper;
}
This has additional undefined behavior, even if you fix the initialization, because you can't use a union in C++ for type punning at all. That is always undefined behavior, although some compilers might allow it to the degree that is allowed in C. Still, the standard does not allow reading fields.upper if wholeReg is the active member of the union (meaning the last member to which a value was assigned).
|
72,471,087 | 72,471,223 | Is std::exchange specialized for atomics? | std::exchange(x,y) assigns x the value y and returns the old value of x.
Is this function specialized for atomic values, i.e. will it use std::atomic_exchange?
I am thinking the answer is no, in that case why not? Was it ever considered? Seems like a good idea to me.
I am using this for resetting a simple counter and was just wondering whether if I make the counter atomic sometime in the future to support threading, whether it will just work or be unsafe.
How can I write generic function where it will use atomic exchange for atomic types and ordinary exchange for ordinary types?
|
How can I write generic function where it will use atomic exchange for
atomic types and ordinary exchange for ordinary types?
You can detect whether obj.exchange(x) is a valid expression (which works for std::atomic) to determine whether to use member function exchange or free function std::exchange.
#include <utility>
template<class T, class U = T>
constexpr
T my_exchange(T& obj, U&& new_value) {
if constexpr (requires { obj.exchange(std::forward<U>(new_value)); })
return obj.exchange(std::forward<U>(new_value));
else
return std::exchange(obj, std::forward<U>(new_value));
}
Demo
|
72,471,250 | 72,486,722 | SFML 3.0 'intersects' function | I downloaded the latest SFML 3.0 source code from github and compiled it using MinGW GCC 11.2 on Windows 10. I'm try to compile example programs from SFML Essentials book.
The code below causes compilation error:
if(playerRect.getGlobalBounds().intersects(targetRect.getGlobalBounds()))
window.close();
error: 'using FloatRect = class sf::Rect<float>' {aka 'class sf::Rect<float>'} has no member named 'intersects'
43 | if(playerRect.getGlobalBounds().intersects(targetRect.getGlobalBounds()))
Looks like there are some breaking changes between SFML 2.5.1 and SFML 3.0 but these changes are not listed on SFML website.
Could someone please let me know how to compile the above code and also point me to any resource which highlights the difference between SFML 2.5.1 and SFML 3.0.
Thanks
| There are API changes in SFML 3.0 which are not compatible with SFML 2.5. For example VideoMode constructor is defined as follows:
// SFML 2.5
VideoMode(unsigned int modeWidth, unsigned int modeHeight, unsigned int modeBitsPerPixel = 32);
// SFML 3.0
explicit VideoMode(const Vector2u& modeSize, unsigned int modeBitsPerPixel = 32);
Hence the below code compiles fine using SFML 2.5 but throws an error when SFML 3.0 is used.
// compiles fine with SFML 2.5
sf::RenderWindow window(sf::VideoMode(640, 480), "SFML-Test");
// Gives following error in SFML 3.0
// error: no matching function for call to 'sf::VideoMode::VideoMode(int, int)'
The table below summaries the changes required to port an application from SFML 2.5 to SFML 3.0.
SFML 2.5
SFML 3.0
sf::VideoMode(640, 480)
sf::VideoMode({640,480})
shape.setOrigin(0, 0)
shape.setOrigin({0, 0})
shape.setPosition(0, 0)
shape.setPosition({0, 0})
shape.setRotation(90.)
shape.setRotation(sf::degrees(90.f))
rect1.getGlobalBounds().intersects(rect2.getGlobalBounds())
rect1.getGlobalBounds().findIntersection(rect2.getGlobalBounds())
The above list is non-exhaustive. I've listed only things which I've learned so far using SFML 3.0.
Also in SFML 3.0, if we ignore the return value of Texture::loadFromImage, we get a nice warning message, thanks to C++17 [[nodiscard]] attribute.
sf::Texture texture;
texture.loadFromImage("sprite.png"); // no warning in SFML 2.5
// SFML 3.0 gives following warning
// warning: ignoring return value of 'bool sf::Texture::loadFromFile(const std::filesystem::__cxx11::path&, const IntRect&)', declared with attribute 'nodiscard'
Also note that sf::Mutex and sf::Lock are no longer supported. They should be replaced with C++11 std::mutex and std::lock_guard.
Hope this helps someone who want to port their application from SFML 2.5/2.6 to SFML 3.0.
|
72,471,395 | 72,477,911 | Array Circular left shift | I am trying to implement AES with an array of boolean values. I am stuck on the ShiftRows() function that left shifts a 4*4 matrix a specified amount.
For example, some random input would create a 128bit array as such:
Enter a message: random bits more!
Before:
01110010 01100001 01101110 01100100
01101111 01101101 00100000 01100010
01101001 01110100 01110011 00100000
01101101 01101111 01110010 01100101
The AES algorithm then states the following left shifts per row:
Row 1: 0 Shift
Row 2: 1 left shift
Row 3: 2 left shifts
Row 4: 3 left shits
Ideally, after the left shift operations, the output should be:
After:
01110010 01100001 01101110 01100100
01101101 00100000 01100010 01101111
01110011 00100000 01101001 01110100
01100101 01101101 01101111 01110010
However, this is what I get:
After:
01110010 01100001 01101110 01100100
01101101 00100000 01100010 01101111
01110011 00100000 01101001 01110100
01101111 01101101 01110010 01100101
This is my current function that works perfectly, however, it breaks down in the final row:
for (int i = 1; i < 4; i++) {May have to research further.
for (int j = 0; j < 4 - i; j++) {
temp2D = matrix[i][mod_floor(-i + j, 4)];
matrix[i][mod_floor(-i + j, 4)] = matrix[i][j];
matrix[i][j] = temp2D;
}
}
The mod_floor() function just returns mod with floor division:
int mod_floor(int shift, int size) {//Size is number of bytes in row
return ((shift % size) + size) % size;
}
I have found a temporary fix by hardcoding the final row:
//Manually does final row shift since algorithm is not working properly for last row in matrix.
temp2D = matrix[3][1];
matrix[3][1] = matrix[3][0];
matrix[3][0] = temp2D;
temp2D = matrix[3][2];
matrix[3][2] = matrix[3][0];
matrix[3][0] = temp2D;
temp2D = matrix[3][3];
matrix[3][3] = matrix[3][0];
matrix[3][0] = temp2D;
However, I am unable to see why it is breaking down at this last row. I know I can create a temporary matrix and copy the updated byte shifts as they occur, although this would ruin the in place algorithm.
Any help would be appreciated, also, let me know if more information can help communicate my problem more clearly.
**EDIT
Using Rotate() worked perfectly. I will study why my algorithm breaks down; which I think corelates with what Goswin is saynig.
| You are swapping numbers instead of shifting. This works for shifting by 1 since the first value ripples along getting swapped over and over. And for 2 since numbers just swap places. But shifting by 3 you only swap the first and second number and nothing else.
for (int j = 0; j < 4 - i; j++) {
with i = 3 that only processes j = 0.
Simplify the whole thing:
copy whole row
copy the row back shifted.
Let the compiler optimize that into loading the 4 numbers into registers and writing them back.
|
72,471,441 | 72,471,599 | C++ Vectors: Error in push_back member function call | I am trying to create the transpose of a matrix - by traversing into 2-D vectors and assigning the values of indices accordingly.
[[2, 4, 6], [6, 8, 9]] --> [[2,6], [4, 8], [6, 9]] // transpose matrix representation
Here's my code
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
vector<vector<int>> result = {};
for (size_t i = 0; i < matrix.size(); i++)
{
for (size_t j = 0; j < matrix[0].size(); j++)
{
int element = matrix[i][j];
result[j][i].push_back(element); // error occurs here
}
}
return result;
}
While calling the function with proper main body - I am getting the error in calling the push_back member function.
The error message
transpose_matrix.cpp:11:30: error: request for member 'push_back' in '(& result.std::vector<std::vector<int> >::operator[](j))->std::vector<int>::operator[](i
', which is of non-class type '__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type' {aka 'int'}
11 | result[j][i].push_back(element);
| ^~~~~~~~~
If you've any alternative suggestion then it'll be also helpful.
| result[j][i] is not a vector, it's an int. Also, you have to at least resize the vector to the number of rows in the transposed matrix (equal to number of columns in the input matrix).
#include <iostream>
#include <vector>
std::vector<std::vector<int>> transpose(std::vector<std::vector<int>>& matrix)
{
std::vector<std::vector<int>> result;
if (matrix.empty())
return result;
result.resize(matrix[0].size());
for (size_t i = 0; i < matrix.size(); i++)
{
for (size_t j = 0; j < matrix[0].size(); j++)
{
int element = matrix[i][j];
result[j].push_back(element);
}
}
return result;
}
int main()
{
std::vector<std::vector<int>> v{
{1,2},
{2,3},
{3,4}
};
auto res = transpose(v);
for (auto const& row : res)
{
for (auto ele : row)
std::cout << ele << " ";
std::cout << std::endl;
}
}
|
72,471,900 | 72,479,469 | Why isn’t my code with C++20 likely/unlikely attributes faster? | Code ran on Visual Studio 2019 Version 16.11.8 with /O2 Optimization and Intel CPU. I am trying to find the root cause for this counter-intuitive result I get that without attributes is statistically faster than with attributes via t-test. I am not sure what is the root cause for this. Could it be some sort of cache? Or some magic the compiler is doing - I cannot really read assembly
#include <chrono>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
#include <cmath>
#include <functional>
static const size_t NUM_EXPERIMENTS = 1000;
double calc_mean(std::vector<double>& vec) {
double sum = 0;
for (auto& x : vec)
sum += x;
return sum / vec.size();
}
double calc_deviation(std::vector<double>& vec) {
double sum = 0;
for (int i = 0; i < vec.size(); i++)
sum = sum + (vec[i] - calc_mean(vec)) * (vec[i] - calc_mean(vec));
return sqrt(sum / (vec.size()));
}
double calc_ttest(std::vector<double> vec1, std::vector<double> vec2){
double mean1 = calc_mean(vec1);
double mean2 = calc_mean(vec2);
double sd1 = calc_deviation(vec1);
double sd2 = calc_deviation(vec2);
double t_test = (mean1 - mean2) / sqrt((sd1 * sd1) / vec1.size() + (sd2 * sd2) / vec2.size());
return t_test;
}
namespace with_attributes {
double calc(double x) noexcept {
if (x > 2) [[unlikely]]
return sqrt(x);
else [[likely]]
return pow(x, 2);
}
} // namespace with_attributes
namespace no_attributes {
double calc(double x) noexcept {
if (x > 2)
return sqrt(x);
else
return pow(x, 2);
}
} // namespace with_attributes
std::vector<double> benchmark(std::function<double(double)> calc_func) {
std::vector<double> vec;
vec.reserve(NUM_EXPERIMENTS);
std::mt19937 mersenne_engine(12);
std::uniform_real_distribution<double> dist{ 1, 2.2 };
for (size_t i = 0; i < NUM_EXPERIMENTS; i++) {
const auto start = std::chrono::high_resolution_clock::now();
for (auto size{ 1ULL }; size != 100000ULL; ++size) {
double x = dist(mersenne_engine);
calc_func(x);
}
const std::chrono::duration<double> diff =
std::chrono::high_resolution_clock::now() - start;
vec.push_back(diff.count());
}
return vec;
}
int main() {
std::vector<double> vec1 = benchmark(with_attributes::calc);
std::vector<double> vec2 = benchmark(no_attributes::calc);
std::cout << "with attribute: " << std::fixed << std::setprecision(6) << calc_mean(vec1) << '\n';
std::cout << "without attribute: " << std::fixed << std::setprecision(6) << calc_mean(vec2) << '\n';
std::cout << "T statistics" << std::fixed << std::setprecision(6) << calc_ttest(vec1, vec2) << '\n';
}
| Per godbolt, the two functions generates identical assembly under msvc
movsd xmm1, QWORD PTR __real@4000000000000000
comisd xmm0, xmm1
jbe SHORT $LN2@calc
xorps xmm1, xmm1
ucomisd xmm1, xmm0
ja SHORT $LN7@calc
sqrtsd xmm0, xmm0
ret 0
$LN7@calc:
jmp sqrt
$LN2@calc:
jmp pow
Since msvc is not open source, one could only guess why msvc would choose to ignore this optimization -- maybe because two branches are all function calls (it's tail call so jmp instead of call) and that's too costly for [[likely]] to make a difference.
But if clang is used, it's smart enough to optimize power 2 into x * x, so different code would be generated. Following that lead, if your code is modified into
double calc(double x) noexcept {
if (x > 2)
return x + 1;
else
return x - 2;
}
msvc would also output different layout.
|
72,472,069 | 72,523,139 | Wrap cstdio print function with C++ variadic template | I'm writing a lightweight parsing library for embedded systems and try to avoid iostream. What I want to do is write variables to a buffer like vsnprintf() but I don't want to specify the format string, much rather the format string should be infered from the arguments passed to my variadic template wrapper. Here's an example:
#include <cstddef>
#include <string>
#include <cstdio>
template <typename... Ts>
void cpp_vsnprintf(char* s, size_t n, Ts&&... arg)
{
std::vsnprintf(s, n, /*how to deduce format string?*/, arg...);
}
int main()
{
char buf[100];
cpp_vsnprintf(buf, 100, "hello", 3, '2', 2.4);
printf(buf);
}
I'm looking for a performant solution, maybe the format string could be composed at compile time? Or is there maybe an stl function that does exactly what I'm asking for?
| I figured it out with some inspiration from this thread
#include <cstdio>
template<class T> struct format;
template<class T> struct format<T*> { static constexpr char const * spec = "%p"; };
template<> struct format<int> { static constexpr char const * spec = "%d"; };
template<> struct format<double> { static constexpr char const * spec = "%.2f";};
template<> struct format<const char*> { static constexpr char const * spec = "%s"; };
template<> struct format<char> { static constexpr char const * spec = "%c"; };
template<> struct format<unsigned long> { static constexpr char const * spec = "%lu"; };
template <typename... Ts>
class cxpr_string
{
public:
constexpr cxpr_string() : buf_{}, size_{0} {
size_t i=0;
( [&]() {
const size_t max = size(format<Ts>::spec);
for (int i=0; i < max; ++i) {
buf_[size_++] = format<Ts>::spec[i];
}
}(), ...);
buf_[size_++] = 0;
}
static constexpr size_t size(const char* s)
{
size_t i=0;
for (; *s != 0; ++s) ++i;
return i;
}
template <typename... Is>
static constexpr size_t calc_size() {
return (0 + ... + size(format<Is>::spec));
}
constexpr const char* get() const {
return buf_;
}
static constexpr cxpr_string<Ts...> ref{};
static constexpr const char* value = ref.get();
private:
char buf_[calc_size<Ts...>()+1] = { 0 };
size_t size_;
};
template <typename... Ts>
auto cpp_vsnprintf(char* s, size_t n, Ts... arg)
{
return snprintf(s, n, cxpr_string<Ts...>::value, arg...);
}
int main()
{
char buf[100];
cpp_vsnprintf(buf, 100, "my R", 2, 'D', 2, '=', 3.5);
printf(buf);
}
Demo
Output:
my R2D2=3.50
You can see that format strings are neatly packed into the binary:
.string "%s%d%c%d%c%.2f"
.zero 1
.quad 15
|
72,472,200 | 72,472,422 | C++ type for functor structs | I am trying to have a single variable with some type that can be assigned to some of the C++ standard functors (eg: std::plus, std::multiplies, etc...)
Here is the definition for std::plus (from this link):
template <class T> struct plus : binary_function <T,T,T> {
T operator() (const T& x, const T& y) const {return x+y;}
};
I tried
#include <functional>
std::binary_function<int, int, int> func = std::plus;
but it doesn't work.
How do I define it properly?
| A single variable to hold all kinds of callables with same signature is std::function<int(int,int)>. Though the functors need to either have the template argument specified or deducde them from arguments:
std::function<int(int,int)> func2 = [](int a,int b){ return std::plus{}(a,b);};
or
std::function<int(int,int)> func = std::plus<int>{};
|
72,472,209 | 72,472,366 | how to convert depth map to 3D points for cv::rgbd::RgbdNormals | I am trying to compute surface normal using OpenCV. Below is the code snippet:
// load 16bit uchar depth image (values are in millimeters)
cv::Mat img = cv::imread("depth.png", CV_16UC1);
// define our camera matrix
cv::Mat k = (cv::Mat1d(3, 3) << 900, 0, 640, 0, 900, 360, 0, 0, 1);
// compute surface normals
cv::Mat normals;
cv::rgbd::RgbdNormals normal_computer(img.rows, img.cols, CV_32F, k, 3);
normal_computer(img, normals);
std::cout << "normals" << std::endl
<< normals << std::endl
<< normals.size() << std::endl
<< normals.channels() << std::endl
<< std::endl;
Unfortunately, it shows the following error:
terminate called after throwing an instance of 'cv::Exception'
what(): OpenCV(4.2.0) ../contrib/modules/rgbd/src/normal.cpp:776: error: (-215:Assertion failed) points3d_ori.channels() == 3 in function 'operator()'
Aborted (core dumped)
As per the documentation, input points should be a rows x cols x 3 matrix of CV_32F/CV64F or a rows x cols x 1 CV_U16S.
Therefore, my question is how to convert depth image to the above suitable format (i.e., rows x cols x 3 matrix of CV_32F/CV64F or a rows x cols x 1 CV_U16S)?
PS: I am using OpenCV v4.2.0 on Ubuntu 20.04 LTS.
| It turned out that there is a function called depthTo3d in OpenCV to do this conversion. Please see following code snippet:
cv::Mat points3d;
cv::rgbd::depthTo3d(img, k, points3d);
After conversion, these points should be given as input as shown below:
normal_computer(points3d, normals);
|
72,472,234 | 72,472,410 | C++ Header & Source Files - What To Include And In Which Order | I just started learning C++ and have trouble understanding the concept of header and source files, specifically which ones I'm supposed to include where.
Suppose I have the classes A and B, each of whose contents are seperated into a header file and a source file, and I have a file in which I want to use those classes.
├ A.h
├ A.cpp
├ B.h
├ B.cpp
└ Main.cpp
Which file do I need to include where, and is it possible to compile/link all files with a single command?
|
Which file do I need to include where
#include directive in fact is very simple preprocessor directive, which just adds content of the specified file into the target file. Conventionally you keep declaration of functions in a header file and definition of the said functions in the corresponding cpp file, and thus you at least want to have the header included there (in your case A.cpp includes A.h and B.cpp includes B.h). Additionally you include headers in any file where you use the functions declared in the headers (e.g. if you use declarations of A.h and B.h in Main.cpp you include those files as well).
P.S. You, however, can define everything right in the header file, next to declarations, but as I said earlier preprocessor doesn't do anything fancy - it just adds the content of the include in the target file, and you usually don't want to have all definitions in place, because each translation unit which has it included will have the same definitions repeated over and over again.
|
72,472,550 | 72,472,621 | long long int ans = a*b VS long long int ans = (long long int) a*b | I've written a code:
int a = 1000000000, b = 1000000000;
long long int ans = a * b;
cout << ans << '\n';
this code is causing overflow. I understand that a * b is causing the problem but I have taken long long int variable to keep a*b.
But look at the following code:
int a = 1000000000, b = 1000000000;
long long int ans = (long long int)a * b;
cout << ans << '\n';
it's working fine causing no overflow. Does it make any temporary variable to hold the value when calculating? Please explain the reason behind this strange overflowing.
| This makes two temporary variables, (long long int)a and (long long int)b. The second conversion is implicit.
Actual compilers might not bother, if the hardware has a 32*32->64 multiply, but officially the conversions have to occur. On 64 bits hardware, it's essentially free when you load an int in a 64 bit register.
|
72,472,629 | 72,473,408 | Iterator over map with uncopyable types | I am trying to implement my own map type and I want an iterator for this map. My understanding is that the value_type of this iterator should be pair<const K, V> (see https://en.cppreference.com/w/cpp/container/map). Now, the iterator's operator* is supposed to return a reference to such a pair. I think this means that I need to store a member in my iterator called current_val so that I can return a reference to it. My question is how to get this to work when V is not copyable. So my implementation looks something like:
template<typename K, typename V>
class Map {
class Iterator {
public:
pair<const K, V>& operator*() { return current_val_; }
Iterator& operator++() {
++index_;
// Now I need to update current_val_;
current_val_ = std::make_pair(keys_[i], vals_[i]);
}
private:
pair<const K, V> current_val_;
int index_ = 0;
K* keys_;
V* vals_;
};
private:
K* keys_;
V* vals_;
};
In this code snippet updating current_val_ doesn't work because it is copying the value into current_val_ but V doesn't support copying.
One possible solution would be to store the data as std::pair<K, V>* instead of storing the keys and values separately, but unfortunately I can't do that.
| You should not create a copy. The iterator should provide some means to modify the element in the container, not a copy of that element.
As you are bound to storing the data as K* and V* you cannot simply return a reference to a std::pair<const K,V> because there is no such element to begin with.
You can take a look at std::vector<bool> as an example of container::reference (the type returned from the iterators dereference) not actually being a reference to the element, but some proxy type. This proxy type should be designed to behave like a std::pair<const K,V>&.
Your iterators merely need to store the index into the member arrays, and either a pointer to those arrays or to the whole map. Then you need to use a proxy that implements the methods you want to support:
class Iterator {
public:
proxy operator*() { return *this; }
Iterator& operator++() {
++index_;
return *this;
}
private:
int index_ = 0;
K* keys_;
V* vals_;
};
struct proxy {
K* key;
V* val;
proxy(const Iterator& it) : key(it.keys_+it.index), val(it.vals_+it.index) {}
// make it look like a std::pair<const K,V>
const K& first() { return *key; }
V& second() { return *val; }
// enable assignment of std::pair<const K,V>
proxy& operator=(const std::pair<const K,V>&);
// comparison with std::pair<const K,V>
bool operator==(const std::pair<const K,V>&);
// ... etc ...
};
Not tested, but I hope you get the idea.
|
72,472,943 | 72,473,133 | Is integer overflow that evil? | Consider the following code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<int> a(n);
int sum = 0;
for (auto &it : a) {
cin >> it;
sum += it;
}
cout << sum << "\n";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
Input like (or anything greater than INT_MAX into k)
5 1234567891564
1 2 3 4 5
makes the program print
0
0 0 0 0 0
What actually happens? We don't use the value of k at all.
| There is actually no integer overflow in your code. Well in a wider sense it there is, but in a more narrow sense integer overflow would happen for example with:
int k = 1234567891564;
What actually happens is that in this line
cin >> n >> k;
operator>> tries to read a int but fails. 1234567891564 is never actually assigned to k. When reading the input fails 0 will be assigned. Hence k comes out as 0.
Once the stream is in an error state, all subsequent calls to operator>> will silently fail as well. You should always check the state of the stream after taking input. For example:
if (std::cin >> n) {
// input succeeded use the value
} else {
// input did not succeed.
std::cin.clear(); // reset all error flags
}
|
72,473,132 | 72,478,402 | Creating a constexpr array from non-constexpr argument | I learnt from here that args is not a constant expression. Now my question is: What should I modify in the given program so that I will be able to have an static_assert in the first variant without getting a compile time error.
In the following code:
#include <array>
template<typename... Args>
auto constexpr CreateArrConst(Args&&... args)
{
std::array arr
{
args...
};
//i want to have an static_assert here without error
return arr;
}
template<typename... Args>
auto constexpr CreateArrConst_NotWorking(Args&&... args)
{
constexpr std::array arr
{
args...
};
static_assert(arr.back() == 4);
return arr;
}
int main()
{
static_assert(CreateArrConst(4).back() == 4);
// uncomment this to reproduce compile error
// static_assert(CreateArrConst_NotWorking(4).back() == 4);
return 0;
}
Here's a link to reproduce:
https://godbolt.org/z/zjrP1Kvn7
| You have to put the arguments into template parameters. Unfortunately it then can't deduce the type of the arguments anymore:
#include <array>
template<typename T, T... args>
auto constexpr CreateArrConst()
{
constexpr std::array arr
{
args...
};
static_assert(arr.back() == 4);
return arr;
}
// cleaner solution requiring C++17
template<auto... args>
auto constexpr CreateArrConstCpp17()
{
constexpr std::array arr
{
args...
};
static_assert(arr.back() == 4);
return arr;
}
int main()
{
static_assert(CreateArrConst<int, 4>().back() == 4); // <-- Works!
static_assert(CreateArrConstCpp17<1, 2, 3, 4>().back() == 4);
return 0;
}
|
72,473,815 | 72,475,646 | Why is heterogenous std::*map lookup opt-in in C++? | To support heterogeneous key lookup for a std::map one has to be a bit more verbose that in the olden days: (taken from the question on how to do it)
int main()
{
{
puts("The C++11 way makes a copy...");
std::map<std_string, int> m;
auto it = m.find("Olaf");
}
{
puts("The C++14 way doesn't...");
std::map<std_string, int, std::less<>> m;
auto it = m.find("Olaf");
}
}
Also see: https://www.cppstories.com/2021/heterogeneous-access-cpp20/ for an explanation.
From this link and from the linked question (and also from N3657) there a a few scattered reasons given as to why this is opt-in. Since I had to do quite some scrolling and I didn't find a succinct summary of the reasons, I would like to put together a summary here that every junior dev understands, as to
Why stupid C++ makes me write that extra std::less<> ??! Why doesn't it just allow transparent heterogeneous comparison with the default type we always used?
;-)
| If std::map would simple support this silently, that is if std::map<KeyT, ValT> would support find(LookupT) for "any compatible" type then:
The abseil page on the matter cites an implicit comparison between double and intthat would be trouble:
implicitly supporting heterogeneous lookup can be dangerous, as the relationship
between values might not be maintained after conversions.
For example, 1.0 < 1.1, but static_cast<int>(1.0) == static_cast<int>(1.1).
Thus, using a double to look up a value in a std::set<int> could lead to incorrect results.
Performance(!) - old code with types that do not support heterogeneous comparison would start to run slower: dyp wrote:
Consider there exists for some type stupid_string only a converting constructor
from char const* but not a comparison operator operator<(stupid_string const&, char const*), only operator<(stupid_string const&, stupid_string const&).
Since std::less<> ((would)) forward to the comparison operator, each comparison will create a new stupid_string.
((instead of just creating the extra comparison object once on the call site of std::find))
|
72,474,030 | 72,474,240 | C++ class declaration after using it | I want to create method with an argument which links to Enemy which is declared later.
Here is my code:
#include <iostream>
#include <vector>
using namespace std;
class Weapon{
public:
int atk_points;
string name;
string description;
void Attack(Entity target){
};
};
class Armor{
public:
int hp_points;
string name;
string description;
int block_chance;
};
class Entity{
public:
int hp;
int atk;
string name;
vector<Weapon> weapons;
vector<Armor> armors;
};
I tried to search for answers, but nothing I found was helpful.
Here's error log:
prog.cpp:9:15: error: ‘Entity’ has not been declared
void Attack(Entity target){
| The problem is that the compiler doesn't know what Entity is at the point where you have used as a parameter type. So you need to tell the compiler that Entity is a class type.
There are 2 ways to solve this both of which are given below:
Method 1
To solve this you need to do 2 things given below:
Provide a forward declaration for the class Entity.
Make the parameter of Attack to be a reference type so that we can avoid unnecessary copying the argument and also since we're providing a member function's definition instead of just declaration.
class Entity; //this is the forward declaration
class Weapon{
public:
int atk_points;
string name;
string description;
//------------------------------v------------>target is now an lvalue reference
void Attack(const Entity& target){
};
};
Working demo
Method 2
Another way to solve this is that you can provide just the declaration for the member function Attack' inside the class and then provide the definition after the class Entity's definition as shown below:
class Entity; //forward declaration
class Weapon{
public:
int atk_points;
string name;
string description;
//------------------------------v----------->this time using reference is optional
void Attack(const Entity& target); //this is a declaration
};
//other code here as before
class Entity{
public:
int hp;
int atk;
string name;
vector<Weapon> weapons;
vector<Armor> armors;
};
//implementation after Entity's definition
void Weapon::Attack(const Entity& target)
{
}
Working demo
|
72,474,389 | 72,474,509 | Adding an explicit constructor makes a construction fail | I would like to understand how the compiler is selecting constructor in the following situation
class Y
{
public:
Y(int) {}
};
class X
{
public:
X(int, int, Y) { cout << "Y\n"; }
//explicit X(int, int, int) { cout << "3 ints\n"; }
};
int main()
{
X x({ 1, 2, 3 }); // Y
}
so that if we uncomment the explicit constructor, there will be no suitable constructor to call.
| X x({ 1, 2, 3 }); is direct initialization.
The behavior of your program can be explained using copy initialization's documentation notes which states:
In addition, the implicit conversion in copy-initialization must produce T directly from the initializer, while, e.g. direct-initialization expects an implicit conversion from the initializer to an argument of T's constructor.
(emphasis mine)
And since in your given example there is no implicit conversion(as you've made that constructor explcit) from the initializer list, you get the mentioned error saying:
error: converting to ‘X’ from initializer list would use explicit constructor ‘X::X(int, int, int)’
You can resolve this error by removing the explicit used for the concerned constructor X::X(int, int, int) as then there will be an implicit conversion available from the initializer list.
but why can't X x({ 1, 2, 3 }); keep using X::X(int, int, Y) when X::X(int, int, int) is explicit?
Because the explicit constructor X::X(int, int, int) that we provide also take part in overload resolution and it is a better match than the other constructor X::X(int, int, Y). And since it is a better match it is preferred but since it is explicit, we get the mentioned error.
|
72,474,878 | 72,475,063 | Is any precision difference between (float + int) and (float + (float)int) in C++? | For example,
If I have int A = 106 and float B = 10.345f, which operation has better precision, A + B or (float)A + B? Or do they actually have the same precision?
| No there is no difference. When adding two arithmetic types, there is a set of implicit conversions that are applied by the compiler. You can find a list of these rules for example on cppreference. In your case rule number 3) applies:
Otherwise, if one operand is float, float complex, or float imaginary,
the other operand is implicitly converted as follows:
integer type to float (the only real type possible is float, which
remains as-is)
[...]
So if you do not explicitely state the conversion using a cast, the compiler implicitely does exactly the same conversion for you. And because the expressions are actually the same, there is also no difference in precision.
|
72,474,896 | 72,474,928 | Is directly putting in binary possible C++ | Is putting in binary as a value possible? I want something like char test = 00101011 and it will become 43. I know this is possible by making a function that converts binary to decimal (which can be inputted) but thats not direct and Im pretty sure it takes time.
| You need to put the prefix 0b.
#include <iostream>
int main()
{
char c = 0b00101011;
std::cout << static_cast<int>(c) << std::endl;
}
|
72,475,728 | 72,476,036 | variadic template deduction with two template argument fails | When I have the class:
template <std::same_as<char> ... Indices>
struct MIndices {
std::tuple<Indices...> indices;
MIndices() = delete;
constexpr explicit MIndices(Indices... args) : indices(args...) {
}
};
The following call works:
MIndices myI('i', 'j', 'l', 'z');
But changing the template to the following:
template <size_t Dims, std::same_as<char> ... Indices>
struct MIndices {
std::tuple<Indices...> indices;
MIndices() = delete;
constexpr explicit MIndices(Indices... args) : indices(args...) {
}
};
And then calling it with
MIndices<4> myI('i', 'j', 'l', 'z');
suddenly fails to deduce the arguments.
Why and how can I fix this?
So in principle I would just like to have a compile-time way to specify
the number of tuple arguments. If this is a bad way for doing it please tell me.
I am using c++20. (gcc-12.1)
| If Dims should equal the number of parameters passed, you should use the sizeof... operator instead of letting the caller specify the size.
CTAD (class template argument deduction) only works when all template arguments of the class are deduced.
The workaround is to let all arguments be deduced. You can wrap the class that deduces the indices into another one that can have the size given explicitly:
#include <iostream>
#include <tuple>
template <size_t Dims>
struct wrapper {
template <std::same_as<char> ... Indices>
struct MIndices {
std::tuple<Indices...> indices;
MIndices() = delete;
constexpr explicit MIndices(Indices... args) : indices(args...) {
}
};
};
int main() {
wrapper<4>::MIndices myI('i', 'j', 'l', 'z');
}
Live Demo
|
72,475,983 | 72,478,795 | opengl glut rotation keyboard directions | i wanna make a small app that allow me to move the triangle to top/bottm left/right.
and when i press w -> rotate above and move above , s => rotate bottom and move bottom ,, d -> rotate right and moves right , a -> rotate left and move left ..
here is my code :
#include <GL/glut.h> // (or others, depending on the system in use)
float xpoint1 = 0.0f;
float xpoint2 = 50.0f;
float xpoint3 = 25.0f;
float ypoint1 = 0.0f, ypoint2 = 0.0f, ypoint3 = 20.0f;
double direction = 0.0;
void Keys(unsigned char key, int x, int y) {
if (key == 'a') {
if (xpoint1 != 0) {
xpoint1 -= 1.0f;
xpoint2 -= 1.0f;
xpoint3 -= 1.0f;
direction = 90.0;
}
}
else if (key == 'd') {
if (xpoint2 != 200) {
xpoint1 += 1.0f;
xpoint2 += 1.0f;
xpoint3 += 1.0f;
direction = 270.0;
}
}
else if (key == 'w') {
if (ypoint3 != 150) {
ypoint1 += 1.0f;
ypoint2 += 1.0f;
ypoint3 += 1.0f;
direction = 0.0;
}
}
else if (key == 's') {
if (ypoint3 != 0) {
ypoint1 -= 1.0f;
ypoint2 -= 1.0f;
ypoint3 -= 1.0f;
direction = 180.0;
}
}
glutPostRedisplay();
}
void resizeChange(int w, int h) {
glClearColor(1.0, 1.0, 1.0, 0.0); // Set display-window color to white.
glMatrixMode(GL_PROJECTION); // Set projection parameters.
glLoadIdentity();
gluOrtho2D(0.0, 200.0, 0.0, 150.0);
glViewport(0, 0, w, h);
glMatrixMode(GL_MODELVIEW);
}
void lineSegment(void)
{
glClear(GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f(0.0, 0.4, 0.2); // Set line segment color to green.
//gluLookAt(0.0, 0.0, 5.0,
// 0.0, 0.0,0.0,
// 0.0, 1.0, 0.0
//);
glLoadIdentity();
glRotated(direction, 0.0, 0.0, 1.0);
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(xpoint1, ypoint1);
glColor3f(0.0, 1.0, 0.0);
glVertex2f(xpoint2, ypoint2);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(xpoint3, ypoint3);
glEnd();
//degree += 1.0;
glFlush(); // Process all OpenGL routines as quickly as possible.
//glutSwapBuffers();
}
void main(int argc, char** argv)
{
glutInit(&argc, argv); // Initialize GLUT.
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Set display mode.
glutInitWindowPosition(50, 100); // Set top-left display-window position.
glutInitWindowSize(600, 600); // Set display-window width and height.
glutCreateWindow("An Example OpenGL Program"); // Create display window.
glutDisplayFunc(lineSegment); // Send graphics to display window.
glutReshapeFunc(resizeChange);
//glutIdleFunc(lineSegment);
glutKeyboardFunc(Keys);
glutMainLoop(); // Display everything and wait.
}
the problem is when i try to change direction of the triangle it disappered ?! , whats the problem ?!
| glRotated rotates around (0, 0). Actually rotate the triangle out of sight. You have to rotate the triangle first and then move it to its place in the world.
Do not change the vertex coordinates but add a translation matrix with glTranslate:
double tx = 0.0, ty = 0.0;
double direction = 0.0;
void Keys(unsigned char key, int x, int y)
{
if (key == 'a') {
tx -= 1.0;
direction = 90.0;
}
else if (key == 'd') {
tx += 1.0;
direction = 270.0;
}
else if (key == 'w') {
ty += 1.0;
direction = 0.0;
}
else if (key == 's') {
ty -= 1.0;
direction = 180.0;
}
glutPostRedisplay();
}
void lineSegment(void)
{
// [...]
glTranslated(tx, ty, 0.0);
glRotated(direction, 0.0, 0.0, 1.0);
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(-25.0, 0.0);
glColor3f(0.0, 1.0, 0.0);
glVertex2f(25.0, 0.0);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(0.0, 20.0);
glEnd();
// [...]
}
|
72,476,043 | 72,544,326 | Should std::string specialize std::less with support for heterogeneous lookup? | Being able to look up a char* in a container with find without needing to create a temporary string object is a Good Thing. See: Avoiding key construction for std::map::find() and https://www.cppstories.com/2021/heterogeneous-access-cpp20/ and ...
There are reasons why C++ could not enable this for any type T used as a key type.
So, as of C++20/23 we are AFAIKT left with:
int main()
{
{
// Slow, constructs temporary
std::map<std_string, int> m;
auto it = m.find("Olaf");
}
{
// "Fast" does not need to construct temporary
std::map<std_string, int, std::less<>> m;
auto it = m.find("Olaf");
}
}
However - I was wondering why std::string doesn't automatically opt-in to this by providing a (partial?) specialization for std::less<std::string>? Has this simply not been specified yet, or are there any legitimate reasons why std::string (or rather std::basic_string<...>) cannot do this?
| I think the primary reason is that nobody proposed it. Nothing happens by magic, it has to be proposed by somebody and then reviewed and approved. If the proposal step doesn't happen, nothing will change.
However, it should be noted that making std::less<std::string> transparent would be a breaking change for types like:
class StupidString
{
std::string m_str1;
std::string m_str2;
public:
// Constructors etc. ...
operator std::string() const { return m_str1; }
std::strong_ordering operator<=>(const std::string& s) const
{ return m_str2 <=> s; }
};
This class behaves differently when compared directly to a std::string or when converted to std::string first and then compared.
Today, passing an instance of this class to map<string, int>::find(const string&) would implicitly convert to std::string and so use m_str1. But if std::less<std::string> was transparent, it would compare using m_str2. That would change behaviour.
Arguably, this class is stupid and deserves to break. Since the addition of <=> the language is much less forgiving of inconsistent comparisons with this kind of odd behaviour. But breaking changes always need to be considered carefully, even if the code that would break looks stupid at first glance.
It would be possible to make std::less<std::string> able to compare directly to just const char* and std::string_view without conversions (which is already true for operator<), e.g.
template<>
struct less<string>
{
bool operator()(const string&, const string&) const noexcept;
// Not in the standard today:
bool operator()(const string&, string_view) const noexcept;
bool operator()(const string&, const char*) const noexcept;
bool operator()(string_view, const string&) const noexcept;
bool operator()(const char*, const string&) const noexcept;
};
But this could also be a breaking change. A type that is convertible to std::string and const char* (or std::string and std::string_view) would now be unable to be passed to std::less<std::string> because it would become ambiguous. That can be solved, e.g.
template<typename T>
concept string_view_or_char_ptr
= same_as<string_view> || same_as<T, const char*> || same_as<T, char*>;
template<>
struct less<string>
{
bool operator()(const string&, const string&) const noexcept;
// Not in the standard today:
template<string_view_or_char_ptr T>
bool operator()(const string&, T) const noexcept;
template<string_view_or_char_ptr T>
bool operator()(T, const string&) const noexcept;
};
But this wouldn't actually help. Because this specialization doesn't define the is_transparent member (because it's not fully transparent, because it only accepts three types, not anything comparable with std::string), the associative containers would not define the additional function templates that take an arbitrary key. And so the extra less<string>::operator() overloads wouldn't be used, and you'd still get a conversion to std::string when you do find("Olaf").
Sorry.
|
72,476,055 | 72,476,108 | Overloading operator+ to add 2 class objects. "C++ expression must be an unscoped integer or enum type" error | I have a Student class which has dynamic int array marks and int variable marksCount. I am trying to overload operator+ to sum 2 Student* objects. It is supposed only to sum their marks.
For example, when adding 2 students (Student* objects) with marks { 2, 3, 4 } + { 1, 5, 2 }, I must have an output of Student* with marks { 3, 8, 6 }.
But my solution throws C++ expression must be an unscoped integer or enum type exception
on
Student* s = s1 + s2; line.
I have already read similar question and answers but unfortunately I haven't become with solution to my problem. Maybe there is something I don't know about how operator+ works?
#include <iostream>
using namespace std;
class Student
{
private:
int* marks;
int marksCount;
public:
Student(int* marks, int marksCount)
{
this->marks = marks;
this->marksCount = marksCount;
}
Student* operator+(Student* st)
{
int* marks = new int[5];
for (int i = 0; i < 5; i++)
{
marks[i] = this->marks[i] + st->getMarks()[i];
}
Student* s = new Student(marks, 5);
return s;
}
int* getMarks()
{
return marks;
}
void setMarks(int* marks, int SIZE)
{
for (int i = 0; i < SIZE; i++)
{
this->marks[i] = marks[i];
}
}
int getMarksCount()
{
return marksCount;
}
void setMarksCount(int count)
{
marksCount = count;
}
static void printMarks(Student* s1)
{
for (int i = 0; i < s1->getMarksCount(); i++)
{
cout << s1->getMarks()[i];
}
}
};
int main()
{
const int SIZE = 5;
int* marks1 = new int[SIZE] { 2, 3, 5, 4, 1 };
int* marks2 = new int[SIZE] { 4, 2, 3, 1, 2 };
Student* s1 = new Student(marks1, SIZE);
Student* s2 = new Student(marks2, SIZE);
Student* s = s1 + s2;
Student::printMarks(s1);
}
| You don't need to use new or pointers here
Student* s1 = new Student(marks1, SIZE);
Student* s2 = new Student(marks2, SIZE);
Student* s = s1 + s2;
so instead
Student s1{marks1, SIZE};
Student s2{marks2, SIZE};
Student s = s1 + s2;
Similarly I would change all your int* to std::vector<int> and basically remove all of the new calls in your entire code.
|
72,476,311 | 72,476,357 | the value is different inside and outside the for-loop C++ | I am a beginner in C++, and I want to write a program that replaces the max value with the min value in an array and vice versa.
#include<iostream>
using namespace std;
int main(){
int num, arr[200],max,min,max_pos,min_pos;
cout <<"enter array size: ";
cin >> num;
for (int i=0; i<num; i++){
cout<<"Enter a value in array position "<<i<<" : ";
cin>>arr[i];
}
for(int i=1, max=arr[0], min=arr[0]; i<num; i++){
if(arr[i]>arr[i-1] && arr[i]>max){
max = arr[i];
max_pos = i;
}
if(arr[i]<arr[i-1] && arr[i]<min){
min = arr[i];
min_pos = i;
}
cout<<"max_in "<<max<<"||"<<"min_in "<<min<<endl;
}
cout<<"max_out "<<max<<"||"<<"min_out "<<min<<endl;
// arr[min_pos] = max;
// arr[max_pos] = min;
// cout<<"max: "<<arr[min_pos]<<" || min: "<<arr[max_pos];
// cout<<"array is ";
// for(int i =0; i<num;i++){
// cout<<arr[i];}
}
this is the output
enter how many number you want inside :4
Enter a value in array position 0 : 2
Enter a value in array position 1 : 1
Enter a value in array position 2 : 4
Enter a value in array position 3 : 6
max_in 2||min_in1
max_in 4||min_in1
max_in 6||min_in1
max 561||min -1343285512
I don't know why the values change outside the loop, where is the mistake?
| Here
for (int i=1, max=arr[0], min=arr[0] ;...
You declare 3 variables, they are called i,max and min. max and min shadow the variables of same name declared outside of the loop.
Do not declare the variables of same name, but use the ones you already declared:
int max = arr[0];
int min = arr[0];
for(int i=1; i<num; i++){
This is a mistake you could have avoided by reading compiler warnings: https://godbolt.org/z/aT753e4nh. Also initializing variables always, and only declare a variable when you can initialize it, would have reduced chances for this kind of mistakes.
|
72,476,814 | 72,476,983 | Error in vector of struct with implemented Functions | I get the Erro:
"no instance of constructor "std::vector<_Ty, _Alloc>::vector
[with _Ty=FunctionToUpdate, _Alloc=std::allocator<FunctionToUpdate>]" matches the argument list"
No matter how I change it, it persists, as long I keep it as a class. If I keep it all in just a simple .cpp without class and header, it all resolves easily.
My.h:
#include <vector>
#include <functional>
#include <iostream>
struct Params
{
std::vector<int> Integers;
std::vector<std::string> Strings;
};
struct FunctionToUpdate
{
int Version;
std::function<void(int, Params)> Function;
Params Parameters;
};
class Error
{
public:
Error();
void testFunctionA(int a, Params p);
void testFunctionB(int a, Params p);
protected:
const static std::vector<FunctionToUpdate> table;
};
Here is my .cpp, please assist me, I can't find the error:
#include "ErrorHandling.h"
Error::Error()
{
for (auto functionToUpdate : table)
{
functionToUpdate.Function(functionToUpdate.Version, functionToUpdate.Parameters);
std::cout << "############################################" << std::endl;
}
std::cout << "Done!" << std::endl;
}
void Error::testFunctionA(int a, Params parameter)
{
//std::cout << "Size Integers: " << parameter.Integers.size() << std::endl;
//std::cout << "Size Strings: " << parameter.Strings.size() << std::endl;
std::cout << a << std::endl;
for (auto& integer : parameter.Integers)
{
std::cout << integer << std::endl;
}
for (auto& integer : parameter.Strings)
{
std::cout << integer << std::endl;
}
}
void Error::testFunctionB(int a, Params parameter)
{
std::cout << a << std::endl;
std::cout << parameter.Integers.at(0) << std::endl;
}
const std::vector<FunctionToUpdate> Error::table
{ // <-- here the Error happens
{ 100, &testFunctionA, { {177}}},
{ 1948, &testFunctionB, { {314}}},
};
int main()
{
Error error;
}
| Your code has a few issues
First, the correct initialization of static member Error::table would be as follows:
const std::vector<FunctionToUpdate> Error::table
{
{ 100, &Error::testFunctionA, { { {177} }, { {"string"} } }},
{ 1948, &Error::testFunctionB, { { {314} }, { {"string"} } } }
};
Note that the syntax &Error::testFunctionA for addressing the member function pointer. Additionally, the Params has two vectors. One is std::vector<int> and the other is std::vector<std::string>. In your code, the std::vector<std::string> has not been mentioned.
In FunctionToUpdate the member function pointer type is wrong. Using typed member function pointer, you could
// forward declaration
class Error;
// member function pointer type
using ErrorFunType = void(Error::*)(int, Params);
struct FunctionToUpdate
{
int Version;
ErrorFunType Function;
Params Parameters;
};
Secondly, the call to pointer to the member function in Error::Error() is wrong. It needs an (Error class) instance to call with. For example:
for (auto functionToUpdate : table)
{
(this->*functionToUpdate.Function)(
functionToUpdate.Version, functionToUpdate.Parameters
);
// or more generic `std::invoke` (since c++17)
// std::invoke(functionToUpdate.Function
// , this, functionToUpdate.Version
// , functionToUpdate.Parameters);
// ...
}
The above changes will make, your code compiles again!
In case of wondering, how to handle the pointer to member function with std::function, (one way) to wrap the instance to call the member along with the std::function type.
Following is the example:
// forward declaration
class Error;
// member function pointer
using ErrorFunType = std::function<void(Error*, int, Params)>;
struct FunctionToUpdate
{
int Version;
ErrorFunType Function;
Params Parameters;
};
now in Error::Error()
Error::Error()
{
for (auto functionToUpdate : table)
{
functionToUpdate.Function(this
, functionToUpdate.Version, functionToUpdate.Parameters);
}
}
See a demo
|
72,477,155 | 72,477,933 | Is the move or the copy constructor used when passing a list into a direct initialization? | Given the following toy code:
class P // with compiler-generated copy constructor and move constructor
{
public:
P(int x, int y) { }
};
int main()
{
P p({x,y});
}
In my current understanding, the {x,y} in P p({x,y}); is converted into an object of type P by implicitly calling the constructor P::P(int x, int y) and passing x and y to it. Usually there is optimization so that this P object is directly constructed as p. Nevertheless, may I ask if this implicit call of P::P(int x, int y) is invoked by the move constructor or the copy constructor (generated by the compiler)?
|
Usually there is optimization so that this P object is directly constructed as p. Nevertheless, may I ask if this implicit call of P::P(int x, int y) is invoked by the move constructor or the copy constructor
Let's see what happens here with and without optimizations in C++17 and prior to C++17.
Prior C++17
Prior to C++17 there was non-mandatory copy elision, which means when you wrote:
P p({x,y}); //here a temporary of type X will be created and then moved/copied
In the above statement, prior to C++17 a temporary of type P will be created which will then be copied/moved using the copy/move constructor. That is the temporary created will be used to copy/move construct p. Since in your example, the compiler will implicitly generate a move constructor, it will be used instead of the implicitly generated copy constructor since a temporary prvalue is used to construct p. It is as-if you wrote:
P p(P{x, y}); //equivalent to what happens without optimization in prior C++17
Note that compilers are allowed to elide this copy/move construction. Thus if you want to see which constructors are called then you can make use of the -fno-elide-constructor that will disable this non-mandatory copy elison.
The output of the program with -fno-elide-constructors prior to C++17 is:
parameterized ctor
move ctor
Again if you don't supply the -fno-elide-constructors flag then the compiler will elide this move construction and you will see the output:
parameterized ctor
C++17 & Onwards
From C++17 there is mandatory copy elision. This means there will be no creation of temporary involve here. The object x will be directly constructed as-if you wrote:
P p(x, y); //this is equivalent to what you wrote from C++17 due to mandatory copy elison
That is, from C++17 onwards, there will be no creation of temporary of type P. This means, the flag -fno-elide-constructors will have no effect in your example from C++17.
We're guaranteed that there is no call to the copy/move constructor from C++17.
|
72,477,749 | 72,477,931 | How to write a lambda function that can only take in int or float pointers? | I need to create a lambda function that can take in either a int * or a float *, e.g., something like
auto func = [](void* ptr) {
// do some assignments with the pointer
}
Currently, I am using the void * approach, but I'm wondering what are some other approaches to accomplish what I want?
I don't have access to C++17 features in my codebase so will have to stick to C++14 or lower semantics.
| C++14 has generic lambdas, meaning you can use SFINAE on them, e.g. in their trailing return types:
#include <type_traits>
template <typename T> struct valid_ptr_type : std::false_type {};
template <> struct valid_ptr_type<int *> : std::true_type {};
template <> struct valid_ptr_type<float *> : std::true_type {};
template <typename T> constexpr bool valid_ptr_type_v{valid_ptr_type<T>::value};
int main() {
// only allow ptr args that fulfills
// the valid_ptr_type_v<decltype(ptr)> trait
auto func = [](auto *ptr) ->
std::enable_if_t<valid_ptr_type_v<decltype(ptr)>> {
// do stuff with ptr
}; // note: void return type (std::enable_if default)
int a{};
float b{};
char c{};
func(&a);
func(&b);
// func(&c); // error
}
What this does behind the hood is to constrain the deduced single template parameter of the template function call operator of the lambda's closure type.
// ~ish
struct AnonClosureTypeOfGenericLambda {
template <typename T,
typename = std::enable_if_t<valid_ptr_type_v<decltype(T*)>>>
void operator()(T* ptr) const { /* ... */ }
};
|
72,477,834 | 72,478,168 | Calculate an answer from a string equation in c++ | I would like to convert a string equation such as 10+20 or even use of numerous operators such as 10+20*5 into an answer such as 110 from a string equation.
I have currently tried looping through each char of the equation string and sorted the numbers and operators, however, I'm not able to get any further than this. Help would be much appreciated!
int calculateFromString(string equation) {
int numbers;
string operators;
// iterate through the equation string
for (int i = 0; i < equation.length(); i++) {
if (equation.charAt(i) >= '0' && equation.charAt(i) <= '9') {
numbers += int(equation.charAt(i));
}
if (equation.charAt(i) == '+' || equation.charAt(i) == '-' || equation.charAt(i) == '*' || equation.charAt(i) == '/') {
operators += equation.charAt(i);
}
}
return numbers;
}
My intended result would be:
calculateFromString("10+20*5")
= 110
I was able to get the operators from the string and store them into the operators string using:
if (equation.charAt(i) == '+' || equation.charAt(i) == '-' || equation.charAt(i) == '*' || equation.charAt(i) == '/') {
operators += equation.charAt(i);
}
However, I'm not sure how I can turn this data into an equation that can be calculated.
| there is several sub problem in what you want to achieve
pseudo code:
for char in equation;
if char == number
do stuff
else if char == operation
do stuff
the number in the equation, will they only be integer ?
that's a single problem its self.
lets assume its only integer...
To test if char is a number you can check if the ascii code is a number (numbers will be between the decimal value of 48 and 57)
Or you can try/catch std::stoi(char)... if no error occurs than its a number.
(At some point you will need std::stoi anyway and try/catch error is a good practice to use)
there's a sub problem to that-> how to determine when the number ends ?
than you will have to create a sub routine to determine the math operation priorities, that won't be an easy task.
first use a std::list or std::vector to store string like that:
[number, operation, number, operation]
then i would use two std::map
one for the numbers and its index
the other one operations and its index
with the index you can determine what operation and numbers goes together
|
72,477,867 | 72,479,296 | Why does C or C++ “-0” not produce a floating-point −0? | I am trying to collect some edge cases for floating-point arithmetic. The thing is, my attempt with printf is not showing me what I want:
#include <cmath>
#include <stdio.h>
#include <complex>
int main() {
double x = -0;
auto y = sqrt(x);
printf("x %f y %f \n", x, y);
return 1;
}
Per IEEE, squareRoot(-0) is -0, but this will print out both x and y to be 0.
Any suggestions on how I can achieve what I want? Would it be through compiler flags or something different?
| 0 is an integer constant, so -0 is also an integer which is still 0.
To get a negative zero, using a floating point constant.
double x = -0.0;
|
72,478,077 | 72,478,414 | How to handle optional class members that are classes | Specifically my problem is that I've created a Texture class (writing OpenGL code). The Texture class handles loading a file into memory, etc. and the constructor takes a filename as its parameter. Here's a snippet of some of the relevant code for that class.
class Texture
{
public:
unsigned char* image;
int width;
int height;
int channels;
GLuint texture_id;
Texture(const char* image_path)
:texture_id(NULL)
I then have a Pyramid class that can include a texture. It might simply be a colored pyramid with no texture though, so the texture attribute is optional.
class Pyramid :
public Shape
{
public:
std::string get_shape_type();
Pyramid(float height, float base_width, glm::vec4 color, glm::mat4 scale, glm::mat4 rotation, glm::mat4 translation);
Pyramid(float height, float base_width, const char * texture_file, glm::mat4 scale, glm::mat4 rotation, glm::mat4 translation);
private:
Texture texture;
Of course, this gives me an error that the Texture class doesn't have a default constructor. What's the general pattern to use in this sort of situation? I tried including texture(NULL) as part of the constructor initialization list for Pyramid since the texture should only be set if a filename is passed in as part of the appropriate constructor, but that didn't clear up the error.
Any suggestions?
| Pointers can help you with that. They can either reference a Texture or nothing (via nullptr).
class Pyramid : public Shape
{
Texture* m_Texture;
Pyramid(Texture *tex = nullptr) m_Texture(tex) {};
};
Notes :
Pyramid may or may not be responsible for creating the texture depending on your need (meaning that the constructors could either require as parameters the Texture* or the filename)
A pointer will allow you to reuse the same Texture between many Shapes without loading them multiple times.
|
72,478,243 | 72,479,906 | Calling C++ function which accepts and returns std::string from Python | I'm trying to call C++ function using ctypes. The function declaration looks like
std::string some_function( const std::string ¶m )
As Python can not interact with C++ directly, I have created a C-wrapper for this function as follows
const char *my_function( const char *param )
{
std::string result = some_function( std::string( param ) );
char *ret = new char[result.length() + 1];
strcpy(ret, result.c_str());
return ret;
}
And Python wrapper
def my_function(param):
func = lib.my_function
func.argtypes = [ctypes.c_char_p]
func.restype = ctypes.c_char_p
result = func(ctypes.c_char_p(param))
return result
But when I try to call Python wrapper with some bytes passed as param, for example
my_function(b'GP\x00\x01\xe6\x10\x00\x00\x01\x01\x00\x00\x00\x1ex\xcb\xa16l\xf1\xbfp\xe6\xaa\xc89\x81\xdd?')
It fails with the following error
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_create
I'm not very good in C and C++. Can you help me to figure out how to create correct wrapper? Thanks.
| Since your data contains embedded nulls, c_char_p won't work as it assumes the returned char* is null-terminated and converts the data up to the first null found to a bytes object. std::string as used also makes that assumption when pass a char* only, so it needs the data length as well.
To manage a data buffer with null content, the size of the input data must be passed in and the size of the output data must be returned. You'll also have to manage freeing the data allocated in the C++ code.
The below code demonstrates everything:
test.cpp - compiled with cl /EHsc /W4 /LD test.cpp with Microsoft Visual Studio.
#include <string>
#include <string.h>
// Windows DLLs need functions to be explicitly exported
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
std::string some_function(const std::string& param) {
return param + std::string("some\x00thing", 10);
}
// pLength is used as an input/output parameter.
// Pass in input length and get output length back.
extern "C" API
const char* my_function(const char* param, size_t* pLength) {
auto result = some_function(std::string(param, *pLength));
auto reslen = result.length();
auto res = new char[reslen];
// Use memcpy to handle embedded nulls
memcpy_s(res, reslen, result.data(), reslen);
*pLength = reslen;
return res;
}
extern "C" API
void my_free(const char* param) {
delete [] param;
}
test.py
import ctypes as ct
dll = ct.CDLL('./test')
# Note: A restype of ct.c_char_p is converted to a bytes object
# and access to the returned C pointer is lost. Use
# POINTER(c_char) instead to retain access and allow it
# to be freed later.
dll.my_function.argtypes = ct.c_char_p, ct.POINTER(ct.c_size_t)
dll.my_function.restype = ct.POINTER(ct.c_char)
dll.my_free.argtypes = ct.c_char_p,
dll.my_free.restype = None
def my_function(param):
# wrap size in a ctypes object so it can be passed by reference
size = ct.c_size_t(len(param))
# save the returned pointer
p = dll.my_function(param, ct.byref(size))
# slice pointer to convert to an explicitly-sized bytes object
result = p[:size.value]
# now the pointer can be freed...
dll.my_free(p)
# and the bytes object returned
return result
result = my_function(b'data\x00more')
print(result)
Output:
b'data\x00moresome\x00thing'
|
72,478,246 | 72,478,611 | Eigen, How to handle element-wise division by zero | How to handle an element-wise division in Eigen if some divider could be 0 ?
I would like the result to be 0.
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
ArrayXd a(3), b(3), c;
a << 1, 2, 0;
b << 1.2, 3.4, 5.6;
c = b / a;
}
| You can handle division by zero by using a binaryExpr:
ArrayXd a(3), b(3);
a << 1, 2, 0;
b << 1.2, 3.4, 5.6;
Eigen::ArrayXd c = a.binaryExpr(b, [](auto x, auto y) { return y==0 ? 0 : x/y; });
|
72,478,338 | 72,478,448 | GoogleMock - Returning a value based on mocked function variables | I'm trying to mock a function that accepts a struct and returns another one. Something like
struct InParams {
int important_value;
int other_value;
}
struct OutParams {
int same_important_value;
int idk_something;
}
virtual OutParams MyClass::TransformParams(const InParams& params){
...
}
When making a mocking function I want the OutParam struct to be dependant of InParam. So I made a mocking class and function
class MockMyClass : public MyClass {
public:
MOCK_METHOD(OutParams, TransformParams,
(const InParams& params), (const, override));
};
OutParams FakeOutParams(const InParams& in_parm){
return {in_parm.important_value, 1};
}
And in expectant call I try to use it like this
auto fake_wrapper = new MockMyClass();
EXPECT_CALL(*fake_wrapper, TransformParams(_))
.WillRepeatedly(
WithArg<0>(Return(FakeOutParams)));
Which fails to compile. I also tried using SaveArgPointee but since InParams wasnt a pointer it also wasn't enough
What can I do to fix my issue?
| When you use Return it takes the object of returned type as argument, by copy. If you want to be more generic, and alter your return value with respect to some logic, use a gmock action. E.g. Invoke will be fine here:
EXPECT_CALL(*fake_wrapper, TransformParams(_))
.WillRepeatedly(Invoke([](const InParams& params) { return FakeOutParams(params); })));
or directly move logic to lambda:
EXPECT_CALL(*fake_wrapper, TransformParams(_))
.WillRepeatedly(Invoke([](const InParams& params) {
return OutParams{ params.important_value, 1 };
})));
|
72,478,576 | 72,478,781 | Using CMake with CPP and ASM on Windows template doesn't work | https://github.com/Ybalrid/cmake-cpp-nasm this project doesn't compile with errors:
[build] cpp.obj : error LNK2019: unresolved external symbol _asm_foo referenced in function _main [C:\Users\[username]\Downloads\cmake-cpp-nasm-master\build\cmake-cpp-nasm.vcxproj] [build] Hint on symbols that are defined and could potentially match: [build] asm_foo
How do I get rid of these errors?
| Ok, I managed to fix this by adding a space:
Old:
if(WIN32)
string(APPEND CMAKE_ASM_NASM_FLAGS "-dWIN32=1")
endif(WIN32)
New:
if(WIN32)
string(APPEND CMAKE_ASM_NASM_FLAGS " -dWIN32=1")
endif(WIN32)
|
72,479,043 | 72,484,675 | fail to wcout wchar[] which from GetWindowText(); | while(TRUE){
HWND window = GetForegroundWindow();
WCHAR str[300] ;
ZeroMemory(str, sizeof(str));
GetWindowTextW(window,str,299);
wcout<<L"11"<<endl;
wcout<<str;
wcout<<L"22"<<endl;
Sleep(1000);
}
this code will output "11",and then stuck. When I try to use char , cout and GetWindowTextA,this loop can run and output English character normal.
With single step debug, the loop still run actually. But don't output anything. And str show window's title normal.
| OK ! Just need to set locale that I forget.
wcout.imbue(locale("your locale"));
|
72,479,081 | 72,480,260 | Static assert that method cannot be called from constructor or destructor | Suppose I have the following classes:
template <typename SELF>
class Base {
protected:
template <int X>
void foo();
};
class Child : public Base<Child> {
public:
Child() {
//I want this to throw a static assertion failure
foo<10>();
}
~Child() {
//Should also static assert here
}
};
Is there any way I make the compiler throw a compile-time assertion failure if the templated member method foo() is called within the constructor or destructor? In other words, I want to prevent, at compile time, the method from being called within the constructor or destructor.
Please don't ask why foo is a template; this is just a simplified example of a more complex project.
| While the OP has acknowledged in the comments that the whole endeavour is probably misguided in their case, the question remains an interesting puzzle.
Performing such a check at runtime is feasible, but it needs to involve code that runs after Child during construction, and code that runs before Child during destruction.
One way to do this would to sandwich Child between Base and some other utility class. For example:
#include <atomic>
#include <cassert>
template<typename SELF>
struct Activator final : SELF {
#ifndef NDEBUG
Activator() {
SELF* self = static_cast<SELF*>(this);
self->alive_state_ = true;
}
~Activator() {
SELF* self = static_cast<SELF*>(this);
self->alive_state_= false;
}
#endif
};
template <typename SELF>
class Base {
#ifndef NDEBUG
friend class Activator<SELF>;
std::atomic<bool> alive_state_= false;
#endif
public:
Base() {}
protected:
template <int X>
void foo() {
assert(alive_state_);
}
};
class ChildImpl : public Base<ChildImpl> {
public:
ChildImpl() {
// fails at runtime
//foo<10>();
}
~ChildImpl() {
// fails at runtime
//foo<10>();
}
void bar() {
foo<10>();
}
};
using Child = Activator<ChildImpl>;
int main() {
Child child;
child.bar();
return 0;
}
This will correctly catch any and invocation of foo<>() during construction/destruction, no matter how convoluted the indirection to the call is.
You can check it out on godbolt: https://gcc.godbolt.org/z/szo6Mhef4
|
72,479,322 | 72,479,487 | How to use x64 assembly with C++ on windows? | cpp.cpp:
#include <iostream>
extern "C" int returnnum();
int main() { std::cout << returnnum() << "\n"; }
asm.asm:
segment .text
global _returnnum
_returnnum:
mov rax, 420
ret
First, I compile the assembly file with nasm -f win64 asm.asm.
Then, I compile the C++ file with g++ cpp.cpp asm.obj.
But this gives me an error:
asm.obj: file not recognized: File format not recognized
collect2.exe: error: ld returned 1 exit status
I know that I can change rax to eax and compile with -f win32 and it'll work, but I want a 64-bit application. Is there any way I can do this?
If this is helpful:
g++ --version: g++ (MinGW.org GCC-6.3.0-1) 6.3.0
nasm --version: NASM version 2.15rc12 compiled on Jun 26 2020
| Based on your information from the comments and your g++ --version output, it looks like you installed plain MinGW (which is purely 32 bit, and works just fine if you only need to build 32 bit executables since Windows supports running 32 bit executables on a 64 bit OS) rather than MinGW-W64, the fork with native support for 64 bit Windows.
You'll need to switch if you want to build true 64 bit executables.
|
72,479,545 | 72,479,667 | Convert between vector::operator[] and vector::at in C++ | vector::at are quite helpful for boundary checking, but will lead to low speed.
So I am wondering whether there is a way to quickly convert code between vector::operator[] and vector::at, so that one for release and one for debug.
Like
If (DEBUG)
{
// Do with .at
}
else
{
// Do with []
}
However, using code like that will import risk that when Do with .at are changed, Do with [] are forgotten to be changed accordingly.
Is there a quick way to convert code between two modes?
|
Like
If (DEBUG)
{
// Do with .at
}
else
{
// Do with []
}
You get something like this by using operator[] and by enabling bounds checking debug mode of the standard library implementation that you use. How to do that, and whether that option exists depends on what implementation you use.
Note that typically the entire project, including all libraries must have been built with the same standard library options. This is a potential problem if you use pre-built libraries.
A universally portable solution is to write a wrapper function that conditionally calls one function or the other depending on build configuration. Downside is that this requires changing all code using the wrapped function to use the custom one.
|
72,479,696 | 72,479,828 | Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h) | I'm getting a runtime error for the below code while solving the Pascal's triangle question on Leetcode:
Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior
I did come up with other code that works, but I'd like to know why I'm getting the error for this code.
vector<vector<int>> generate(int numRows) {
vector<vector<int>> v(numRows);
vector<int> q;
for(int i=0;i<numRows;i++){
q.resize(i+1);
q[0]=q[i]=1;
for(int j=1;j<i;j++){
q[j]=v[i-1][j-1]+v[i-1][j];
}
v.push_back(q);
q.clear();
}
return v;
}
| You construct vector v with numRows number of elements. And then you iterate from 0 to numRows - 1 and in each iteration, you add a new vector to the and of vector v, so you end up with a vector holding 2 * numRows number of elements instead of numRows number of elements.
Instead of vector<vector<int>> v(numRows); you should use v.reserve(numRows). Here is full code:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> v;
v.reserve(numRows);
vector<int> q;
for(int i=0;i<numRows;i++){
q.resize(i+1);
q[0]=q[i]=1;
for(int j=1;j<i;j++){
q[j]=v[i-1][j-1]+v[i-1][j];
}
v.push_back(q);
q.clear();
}
return v;
}
|
72,480,093 | 72,480,446 | Convert array of bits to an array of bytes | I want to convert an array of bits (bool* bitArray) where the values are 1s and 0s into an array of bytes (unsigned char* byteArray) where the values at each index would be one byte.
For ex, index 0~7 in bitArray would go into byteArray[1].
How would I go about doing this? Assuming that I already have an array of bits (but the amount would be subject to change based on the incoming data).
I am not worried about having it divisible by 8 because I will just add padding at the end of the bitArray to make it divisible by 8.
| Just just use bit shifts or a lookup array and and combine numbers with 1 bit set each with bitwise or for 8 bits at a time:
int main() {
bool input[] = {
false, false, false, true, true, true, false, false, false,
false, false, false, true, true, true, false, false, false,
false, false, false, true, true, true, false, false, false,
false, false, false, true, true, true, false, false, false,
};
constexpr auto len = sizeof(input) / sizeof(*input);
constexpr size_t outLen = ((len % 8 == 0) ? 0 : 1) + len / 8;
uint8_t out[outLen];
bool* inPos = input;
uint8_t* outPos = out;
size_t remaining = len;
// output bytes where there are all 8 bits available
for (; remaining >= 8; remaining -= 8, ++outPos)
{
uint8_t value = 0;
for (size_t i = 0; i != 8; ++i, ++inPos)
{
if (*inPos)
{
value |= (1 << (7 - i));
}
}
*outPos = value;
}
if (remaining != 0)
{
// output byte that requires padding
uint8_t value = 0;
for (size_t i = 0; i != remaining; ++i, ++inPos)
{
if (*inPos)
{
value |= (1 << (7 - i));
}
}
*outPos = value;
}
for (auto v : out)
{
std::cout << static_cast<int>(v) << '\n';
}
return 0;
}
The rhs of the |= operator could also be replaced with a lookup in the following array, if you consider this simpler to understand:
constexpr uint8_t Bits[8]
{
0b1000'0000,
0b0100'0000,
0b0010'0000,
0b0001'0000,
0b0000'1000,
0b0000'0100,
0b0000'0010,
0b0000'0001,
};
...
value |= Bits[i];
...
|
72,480,360 | 72,481,352 | Problems discovering glibc version in C++ | My application is distributed with two binaries. One which is linked to an old glibc (for example, 2.17) and another binary that targets a newer glibc (for example, 2.34). I also distribute a launcher binary (linked against glibc 2.17) which interrogates the user's libc version and then runs the correct binary.
My code to establish the user's libc looks something like the following:
std::string gnu(gnu_get_libc_version());
double g_ver = std::stod(gnu);
if(g_ver >= 2.34)
{
return GLIBC_MAIN;
}
else
{
return GLIBC_COMPAT;
}
This works perfectly for the best part, however, some of my users report that despite having a new glibc, the old glibc binary is actually run. I have investigated this and have discovered that double g_ver is equal to 2, not 2.34 as it should be. That is, the decimal part is missing. gnu_get_libc_version() always has the correct value so it must be a problem when converting the string to a double.
I have also tried boost::lexical_cast but this has the same effect.
std::string gnu(gnu_get_libc_version());
//double g_ver = std::stod(gnu);
double glibc = boost::lexical_cast<double>(gnu);
if(g_ver >= 2.34)
{
return GLIBC_MAIN;
}
else
{
return GLIBC_COMPAT;
}
Needless to say, I am unable to reproduce this behaviour on any of my computers even when running the exact same distribution / version of Linux as affected users.
Does anybody know why boost::lexical_cast or std::stod sometimes misses the decimal part of the version number? Is there an alternative approach to this?
UPDATE
Upon further tests, this problem is introduced when using a different locale. I set my locale to fr_FR.UTF-8 on a test machine and was able to reproduce this problem. However, the output of gnu_get_libc_version() seems to be correct but std::stod is unable to parse the decimal point part of the version.
Does anybody know how to correct this problem?
| The fundamental problem is that the glibc version is a string and not a decimal number. So for a "proper" solution you need to parse it manually and implement your own logic to decide which version is bigger or smaller.
However, as a quick and dirty hack, try inserting the line
setlocale(LC_NUMERIC, "C");
before the strtod call. That will set the numeric locale back to the default C locale where the decimal separator is .. If you're doing something that needs correct locales later in the program you need to set it back again. Depending on how your program initialized locales earlier, something like
setlocale(LC_NUMERIC, "");
should reset it back to what the environment says the locale should be.
|
72,480,374 | 72,480,698 | C4389 signed/unsigned mismatch only for x86 compilation c++ | I am seeing a C4389: "'==': signed/unsigned mismatch" compiler warning when I execute the following code in Visual Studio using the x86 compiler using a warning level of 4.
#include <algorithm>
#include <vector>
void functionA()
{
std::vector<int> x(10);
for(size_t i = 0; i < x.size(); i++)
{
if (std::find(x.begin(), x.end(), i) != x.end())
continue;
}
}
Can someone explain to me why this happens and how I can resolve this?
Here is a link https://godbolt.org/z/81v3d5asP to the online compiler where you can observe this problem.
| You have declared x as a vector of int – but the value you are looking for in the call to std::find (the i variable) is a size_t. That is an unsigned type, hence the warning.
One way to fix this is to cast i to an int in the call:
if (std::find(x.begin(), x.end(), static_cast<int>(i)) != x.end())
Another option (depending on your use case) would be to declare x as a vector of an unsigned integer type:
std::vector<unsigned int> x(10);
|
72,480,377 | 72,492,287 | Replacing define statement with actual code | I know that #define is not really good to use, I am not sure if that's a duplicate but I couldn't find what's the best way is to do this:
I have a program that uses a definition like:
#define True GetObject(true)
I need to replace the define statement with actual code
but I can't think of a way to make it so the following code:
int main() {
auto c = True;
return 0;
}
turns into this at compile time:
int main() {
auto c = GetObject(true);
return 0;
}
Summary:
I want an exact replacement of "define" as code, I found something like an inline function
could help, but is there a way to make an inline variable?
I tried the following but ended up with an error
inline Object True = GetObject(true);
NOTE: I can't make Object/GetObject a constexpr class
NOTE 2: I'd like to avoid turning True to True() if that's possible
This is basically a question for educational purposes but I would like to use it in a small library I am writing, If you could tell me what would be the best way to do this I'd be really happy
Thanks!!!
EDIT 1
As the first above is not quite clear, I'd like True to call GetObject(true) function every time
The returned value is going to be the same but the function call is necessary
EDIT 2
I didn't think it is necessary to explain this but, the library I am creating is a simple layer (that's not really important for this),
The macro name True is completely random, it could be named something completely different (I am just using it for testing)
The macro is used to create a Class that I need to use a lot in my code and I also need it to create a new instance of the class (not just a copy)
I also need to update the class a lot so to add more constants in the constructor I would need to have some simple way to do, I don't think it would be good to go in each of my 10 headers/sources and replace every instance
with the values that represent 'True' and other states.
the part about removing () is because I don't think it's convenient to see a lot of parenthesis in something that looks like a variable (or maybe some kind of compile-time constant?)
| The following is probably similar in principle to your code.
It is solved with #define and sets a serialno to each Object and prints something out to the console:
#define True GetObject(true)
#define False GetObject(false)
#include <iostream>
using namespace std;
class Object {
public:
Object(bool b, int serial) : _b(b), _serialno(serial) {};
bool _b;
int _serialno;
};
Object GetObject(bool b) {
static int curserial = 0;
Object result(b, ++curserial);
cout << "Created Object with serialno " << result._serialno << " and value " << boolalpha << result._b << endl;
return result;
}
int main() {
auto c = True;
auto d = True;
auto e = False;
return 0;
}
which generates the output
Created Object with serialno 1 and value true
Created Object with serialno 2 and value true
Created Object with serialno 3 and value false
Now we change it to the same result without '#define':
#include <iostream>
using namespace std;
class Object;
void GotObject(Object& o);
class Object {
public:
Object(bool b) : _b(b), _serialno(++curserial) {};
Object(const Object& other) : _b(other._b), _serialno(++curserial) {
GotObject(*this);
};
bool _b;
int _serialno;
inline static int curserial = 0;
};
void GotObject(Object& o) {
cout << "Created Object with serialno " << o._serialno << " and value " << boolalpha << o._b << endl;
}
inline Object True(true);
inline Object False(false);
int main() {
auto c = True;
auto d = True;
auto e = False;
return 0;
}
Output:
Created Object with serialno 3 and value true
Created Object with serialno 4 and value true
Created Object with serialno 5 and value false
Each time we assign the values of True or False to new variables the copy constructor is called and can do, whatever you did in GetObject.
Small variant: If we choose this alternative custom constructor instead of the one in the code,
Object(bool b) : _b(b), _serialno(0) {};
we would get as output:
Created Object with serialno 1 and value true
Created Object with serialno 2 and value true
Created Object with serialno 3 and value false
The difference is, whether the serialno is also counted up for True and False themselves or only after assigning those to a variable.
For Generating True and False the first constructor is called, for the following assignments to other variables, the second constructor.
You could also keep a bool _original variable inside Object to only call GetObject(), which states whether you copy from the original True or False. It is true only for True and False. You can recognize those by them calling a special constructor. If you want to make it safe to use, you can make that constructor private, so it can only be called by friend functions or by static factory methods.
In the following code, GotObject is not called from assigning from c to f.
#include <iostream>
using namespace std;
class Object;
void GotObject(Object& o);
class Object {
public:
Object(bool b) : _b(b), _serialno(0), _original(true) {};
Object(const Object& other) : _b(other._b), _original(false), _serialno(0) {
if (other._original)
GotObject(*this);
};
bool _original;
bool _b;
int _serialno;
};
void GotObject(Object& o) {
static int curserial = 0;
o._serialno = ++curserial;
cout << "Created Object with serialno " << o._serialno << " and value " << boolalpha << o._b << endl;
}
inline Object True(true);
inline Object False(false);
int main() {
auto c = True;
auto d = True;
auto e = False;
auto f = c;
return 0;
}
Output:
Created Object with serialno 1 and value true
Created Object with serialno 2 and value true
Created Object with serialno 3 and value false
|
72,480,399 | 72,484,629 | Does compiler need to care about other threads during optimizations? | This is a spin-off from a discussion about C# thread safety guarantees.
I had the following presupposition:
in absence of thread-aware primitives (mutexes, std::atomic* etc., let's exclude volatile as well for simplicity) a valid C++ compiler may do any kinds of transformations, including introducing reads from the memory (or e. g. writes if it wants to), if the semantics of the code in the current thread (that is, output and [excluded in this question] volatile accesses) remain the same from the current thread's point of view, that is, disregarding existence of other threads. The fact that introducing reads/writes may change other thread's behavior (e. g. because the other threads read the data without proper synchronization or performing other kinds of UB) can be totally ignored by a standard-conform compiler.
Is this presupposition correct or not? I would expect this to follow from the as-if rule. (I believe it is, but other people seem to disagree with me.) If possible, please include the appropriate normative references.
| Yes, C++ defines data race UB as potentially-concurrent access to non-atomic objects when not all the accesses are reads. Another recent Q&A quotes the standard, including.
[intro.races]/2 - Two expression evaluations conflict if one of them modifies a memory location ... and the other one reads or modifies the same memory location.
[intro.races]/21 ... The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, ...
Any such data race results in undefined behavior.
That gives the compiler freedom to optimize code in ways that preserve the behaviour of the thread executing a function, but not what other threads (or a debugger) might see if they go looking at things they're not supposed to. (i.e. data race UB means that the order of reading/writing non-atomic variables is not part of the observable behaviour an optimizer has to preserve.)
introducing reads/writes may change other thread's behavior
The as-if rule allows you to invent reads, but no you can't invent writes to objects this thread didn't already write. That's why if(a[i] > 10) a[i] = 10; is different from a[i] = a[i]>10 ? 10 : a[i].
It's legal for two different threads to write a[1] and a[2] at the same time, and one thread loading a[0..3] and then storing back some modified and some unmodified elements could step on the store by the thread that wrote a[2].
Crash with icc: can the compiler invent writes where none existed in the abstract machine? is a detailed look at a compiler bug where ICC did that when auto-vectorizing with SIMD blends. Including links to Herb Sutter's atomic weapons talk where he discusses the fact that compilers must not invent writes.
By contrast, AVX-512 masking and AVX vmaskmovps etc, like ARM SVE and RISC-V vector extensions I think, do have proper masking with fault suppression to actually not store at all to some SIMD elements, without branching.
When using a mask register with AVX-512 load and stores, is a fault raised for invalid accesses to masked out elements? AVX-512 masking does indeed do fault-suppression for read-only or unmapped pages that masked-off elements extend into.
AVX-512 and Branching - auto-vectorizing with stores inside an if() vs. branchless.
It's legal to invent atomic RMWs (except without the Modify part), e.g. an 8-byte lock cmpxchg [rcx], rdx if you want to modify some of the bytes in that region. But in practice that's more costly than just storing modified bytes individually so compilers don't do that.
Of course a function that does unconditionally write a[2] can write it multiple times, and with different temporary values before eventually updating it to the final value. (Probably only a Deathstation 9000 would invent different-valued temporary contents, like turning a[2] = 3 into a[2] = 2; a[2]++;)
For more about what compilers can legally do, see Who's afraid of a big bad optimizing compiler? on LWN. The context for that article is Linux kernel development, where they rely on GCC to go beyond the ISO C standard and actually behave in sane ways that make it possible to roll their own atomics with volatile int* and inline asm. It explains many of the practical dangers of reading or writing a non-atomic shared variable.
|
72,480,439 | 72,480,620 | What components of a machine affect the machine code produced given a C++ file input? | I wrote this question What affects generated machine code at each step of the compilation process? and realized that is was much too broad. So I will try to ask each component of it in a different question.
The first question I will ask is, given an arbitrary C++ file what affects the resulting executable binary file it produces? So far I understand each of the following play a role
The CPU architecture like x86_64, ARM64, Power PC, Microblaze, ect.
The kernel of a machine like Linux kernel v5.18, v5.17, a Windows Kernel version, a Mac kernel version ect.
The operating system such as Debian, CentOS, Windows 7, Windows 10, Mac OS X Mountain Lion, Mac OS X Sierra.
Not sure what the OS changes on top of the kernel changes.
Finally the tools used to compile, assembly and link. Things like GCC, Clang, Visual Studio (VS), GNU assembler, GNU compiler, VS Compiler, VS linker, ect.
So the 2 questions I have from this are
Is there some other component that I left out that affects how the final executable looks like?
And does the operating system play a role in affecting the final executable machine code? Because I thought it would all be due to the kernel.
| The main one I think you're missing is the Application Binary Interface. Part of the ABI is the calling convention, which determines certain properties of register usage and parameter passing, so these directly affect the generated machine code.
The kernel has a loader, and that loader works with file formats, like ELF or PE. These influence the machine code by determining the layout of the process and how the program's code & data are loaded into memory, and how the machine code instructions access data and other code. Some environments want position independent code, for example, which affects some of the machine code instructions.
The CPU architecture like x86_64, ARM64, Power PC, Microblaze, ect.
Yes. The instruction set architecture defines the available instructions to use, which in turn define the available CPU registers and how they can be used as well as and sizes of things like pointers.
The kernel of a machine like Linux kernel v5.18, v5.17, a Windows Kernel version, a Mac kernel version ect.
Not really. The operating system choice influences the ABI, which is very relevant, though.
The operating system such as Debian, CentOS, Windows 7, Windows 10, Mac OS X Mountain Lion, Mac OS X Sierra.
The operating system usually dictates the ABI, which is important.
the tools used to compile, assembly and link. Things like GCC, Clang, Visual Studio (VS), GNU assembler, GNU compiler, VS Compiler, VS linker, ect.
Of course, different tools produce some different machine code, sometimes the differences are equivalent, though some tools produce better machine code than others for some inputs.
|
72,480,933 | 72,495,767 | CRTP and Incomplete Types | I'd like a short clarification on how complete types relate to CRTP. I thought this question was somewhat related. However, my question here question pertains to CRTP where a derived class member function explicitly calls the base class member function, which in turn calls a derived function. This appears different from calling a base class function on a derived type once within the main routine.
I have also read this question where it was explained that the static constexpr members of the base class that make use of the derived class are not initialized until the derived class is seen by the compiler and is complete. However in that case, the derived class was also templated.
Here is my question. Consider
template<typename D> struct B{
void foo() const { static_cast<const D*>(this)->baz(); }
};
struct D : B<D> {
void bar() const { foo(); }
void baz() const {}
};
As I understand, each D remains an incomplete type until the closing brace of the class. I also understand that member function templates are not instantiated until they are used. Thus, if we ignore D::bar for now, it makes sense that the following is valid in main:
D d; d.foo();
What I need further clarification about is what constitutes use? For example, in defining D::bar, there is a call to B::foo (so that function is presumably instantiated there) which would then require D to be a complete type. But at the point where D::bar is being defined, D is not complete. Or is it?
I thought perhaps what could be happening is that where D::bar is being defined and calls B::foo, it forces the compiler to make a declaration for B::foo (no definition required). And perhaps the definition does not happen until D::bar is actually called at some other point. But I ran this at C++ Insights and became more confused as the explicit specialization of B to B<D> happens even before D is declared. Clarification would be appreciated!
| Using B<D> as base class for D requires B<D> to be a complete class. Hence it will cause implicit instantiation of B<D>.
The point of instantiation of the class specialization is immediately before the namespace scope declaration requiring it, meaning before the definition of D. (by [temp.point]/4)
The implicit instantiation of B<D> does not cause implicit instantiation of the member function definition for foo. Hence D won't be required to be complete here.
The definition
void bar() const { foo(); }
has an ODR-use of foo. Therefore it will cause implicit instantiation of B<D>::foo.
The points of instantiation for a member function specialization are immediately after the namespace scope declaration and at the end of the translation unit. (by [temp.point]/1 and [temp.point]/7.1)
Both of these are after the definition of D and therefore D will be complete at these points. Consequently static_cast<const D*>(this)->baz(); is not a problem.
Note that D is not a template. The template instantiation rules do not apply to it. It doesn't matter whether bar is used or referred to at all. Neither does it matter whether you use D d; d.foo(); or anything at all following the definition of D.
|
72,481,316 | 72,481,630 | Shortest distance around a circular axis; using degrees | Premise
A simple SDL program of an entity (single dot/pixel) that rotates around (in a circle), then moves in that direction.
Problem
I'm unable to properly calculate the shortest distance from one degree to another; especially when those degrees cross the bounds of the 360/0 mark.
Goal
Calculate whether the shortest distance from an 'origin' degree to a 'destination' is Clockwise, or Counter Clockwise, while factoring in the transversal over the 360 degree mark.
Program Display
Attempting to fulfill these concepts
Code
Main
void draw ( )
{
/* - - - - - - - - - - - - - - - - - Init - - - - - - - - - - - - - - - - - */
SDL_Event sdl_event;
WALKER walker;
walker = { POINT { WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2 } }; // Entity in center
/* - - - - - - - - - - - - - - - - - Init - - - - - - - - - - - - - - - - - */
int degree = 0;
walker.rotation.set ( degree, generate_random ( 0, 360 ) );
while ( run_loop ) // Display Animation
{
set_render_draw_colors ( );
SDL_RenderDrawPoint ( renderer, walker.origin.x, walker.origin.y ); // Draw: entity dot
POINT point = walker.rotate ( degree ); // Create: pivot point & rotate per degree
SDL_RenderDrawLine ( renderer, walker.origin.x, walker.origin.y, point.x, point.y ); // Draw: sightline with acquired orientation
SDL_RenderPresent ( renderer );
degree++;
degree = ( degree > 359 ) ? 0 : degree;
if ( degree == walker.rotation.destination )
walker.rotation.set( walker.rotation.destination, generate_random ( 0, 360 ) );
while ( SDL_PollEvent ( &sdl_event ) )
{
if ( sdl_event.type == SDL_QUIT )
run_loop = false;
else
break;
}
}
}
Walker
struct WALKER
{
POINT origin = { 0, 0 };
POINT point = { 0, 0 };
ROTATION rotation;
int point_length = 35;
time_t time_seed;
// Constructors ......................................................... //
WALKER ( POINT origin, POINT point )
{
this->origin = origin;
this->point = point;
}
// Constructors (Generic) ... //
WALKER ( ) { };
~WALKER ( ) { };
// Functions ............................................................ //
double convertToRadian ( int degree )
{
return ( degree * PI / 180 );
}
int convertToDegree ( float radian )
{
return ( radian * 180 ) / PI;
}
POINT rotate ( int degree )
{
POINT point = { this->origin.x + this->point_length, this->origin.y };
double radians = convertToRadian ( degree );
double sine = sin ( radians );
double cosine = cos ( radians );
point.x -= this->origin.x; // translate point back to origin
point.y -= this->origin.y;
double x_new = point.x * cosine - point.y * sine; // rotate point
double y_new = point.x * sine - point.y * cosine;
point.x = x_new + this->origin.x; // translate point back
point.y = y_new + this->origin.y;
return point;
}
};
| If it wasn't for the 0/360 cross, it would just be a matter of getting the difference between the two angles, the sign of that difference would tell you if it's clockwise or not.
On, top of that, if you get the difference between two angles for which the shortest path DOES cross the boundary, you'd end up with a difference with an absolute value greater than 180 (since the distance ends up going around the circle the other way.
So all you need to do is get the difference between the two angles, and "fix" it if it's too large.
int angle_diff(int from, int to) {
// Use a modulo to handle angles that go around the circle multiple times.
int result = to % 360 - from % 360;
if(result > 180) {
result -= 360;
}
if(result <= -180) {
result += 360;
}
return result;
}
|
72,481,395 | 72,481,419 | C++ access object behind iterator in loop | I have created a list of objects of a class.
The class has an overloaded ostream << operator to output customer data in a structured way.
What I am trying to do is loop over the list of objects and call cout on the object in the iteration.
Code for the loop is as follows:
for (list<Kunde>::iterator it = this->kun_list.begin(); it != this->kun_list.end(); ++it) {
cout << it << endl;
}
With Kunde being the class with the overloaded << operator and kun_list being the list of objects of type Kunde.
friendly overload within the Kunde class:
friend ostream& operator<< (ostream& os, Kunde& kd) {
os << "__Kundendaten__" << endl;
os << "Name: " << kd.vorname << " " << kd.name << endl;
os << "Geburtsjahr: "<< kd.geburtsjahr << endl;
os << "Adresse: " << kd.strasse << " " << kd.hausnummer << endl << kd.plz << " " << kd.ort << endl;
os << "Telefon: " << kd.telefonnummer << endl;
string fschein = "Nein.";
if (kd.klasse_a_vorhanden) {fschein = "Ja.";}
os << "Führerschein Kl. A vorhanden: " << fschein << endl;
return os;
};
The above loop does not work because I am using the list iterator instead of an object of class Kunde. I can access members of Kunde via it→member but how do I use that iterator as reference to the whole object?
Thanks!
| Use a const reference loop over the container:
for (const auto & kunde : kun_list) {
cout << kunde << endl;
}
Obviously you also have to fix <<:
friend ostream& operator<< (ostream& os, const Kunde& kd) {...}
|
72,481,445 | 72,481,446 | COUT gives strange number for simple C++ code | I am trying to add a ASCII asterisk (*) frame around the hello world in a very simple C++ code.
It works but gives this strange number before the frame. Here is my sample code.
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Please enter your name" << endl;
string name;
cin >> name;
string greeting = "Hello, " + name + "!";
string spaces(greeting.size(), ' ');
string stars(greeting.size(), '*');
cout << '**' << stars <<'**' << endl;
cout << '* ' << spaces <<' *' << endl;
cout << '* ' << greeting << ' *' << endl;
cout << '**' << stars <<'**' << endl;
cout << '* ' << spaces <<' *' << endl;
return 0;
}
Output
Please enter your name
tester
10794**************10794
10784 8234
10784Hello, tester!8234
10794**************10794
10784 8234
Press any key to continue . . .
Why does it add these numbers before and after the string? Please help. Thanks.
| Try double quote, so it looks like this:
cout << "**" << stars <<"**" << endl;
:-)
|
72,481,511 | 72,481,605 | Return type of decltype() | In the below code, why decltype(++c) returns int& instead of int whereas decltype(a++) return int.
#include <iostream>
#include <typeinfo>
int main()
{
int32_t a {};
decltype(a++) b; // OK
int32_t c{};
decltype(++c) d; // error: 'd' declared as reference but not initialized
std::cout << "typeid(b) = " << typeid(b).name() << std::endl;
std::cout << "typeid(d) = " << typeid(d).name() << std::endl;
}
| The result of the built-in pre-increment operator is an lvalue referring to the operand (which then holds the value after the increment). This means that, for example, ++a = 1; is valid. The result of ++a refers to the variable a, which can be assigned a value 1.
The result of the built-in post-increment operator is a prvalue of the previous value of the operand (it couldn't be an lvalue referring to the operand since post-increment is supposed to give the previous value before the increment). This means that, eg a++ = 1; is not valid since the result of a++ is not referring to a, but is just the original value of a, and a value can't be assigned a value.
decltype applied to a prvalue expression gives a non-reference. Applied to an lvalue expression, it gives an lvalue reference to the expression's type. This mimics the return types you would need to use to get the same value categories for the expressions if you overloaded the increment operators.
|
72,482,493 | 72,483,088 | removing x from a string using pass by pointer with recursion | I wrote this code to remove all occurrences of x from the string using recursion
#include <bits/stdc++.h>
using namespace std;
void removex(string str)
{
if (str.length()==0)
{
return;
}
if (str[0] != 'x')
{
removex(str.substr(1,str.length()));
}
int i = 1;
for (; str[i] != '\0'; i++)
{
str[i-1]=str[i];
}
str[i - 1] = str[i];
removex(str);
// cout<<"strq"<<str<<endl;
}
int main()
{
int t;
cin >> t;
while (t--)
{
string str;
cin >> str;
removex(str);
cout << str << endl;
}
return 0;
}
however it's pass by value and If I try using pass by reference it gives an error as
initial value of reference to non-const must be an lvalueC. which means I need to make the reference constant which is not suitable for rest of the code. I tried pass by pointer and using arrow operator however unable to get value at index and not sure how to make recursion call. to pass address or ponter? can someone modify it accordingly?
| Doing this with std::string and recursion is a formidable template for insanity. The erase/remove idiom exists for just this purpose, functions iteratively, and is highly efficient. Best of all, it already exists; all you have to do is set up the calls.
That said, if you're bent on doing this recursively (and inefficiently) you need to convey the result back to the caller (including the recursive calls) somehow. The following does that using the function return type, which is std::string. This also uses the global free operator + that allows concatenation of a char + std::string to return a new string:
#include <iostream>
#include <string>
std::string removex(std::string str)
{
if (!str.empty())
{
if (str[0] == 'x')
str = removex(str.substr(1));
else
str = str[0] + removex(str.substr(1));
}
return str;
}
int main()
{
std::string str = "Remove all x chars from this string.";
std::cout << "Before: " << str << '\n';
std::cout << "After: " << removex(str) << '\n';
return 0;
}
Output
Before: Remove all x chars from this string.
After: Remove all chars from this string.
That said, that isn't the way I'd do this. I'd use the erase/remove idiom which would be much faster, and much more memory efficient.
|
72,482,660 | 72,482,749 | I'm getting an out of range error on my Leetcode program | So, I'm working on a relatively simple program on leetcode (https://leetcode.com/problems/plus-one/). I'll copy the description below:
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example: if digits = [1,2,3] then after digits = [1,2,4], because 123 + 1 = 124.
Anyways my code works for all the inputs I've tried except when the array consists of all 9's. I'm not sure why but I get an out of range error:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
I know that my code so far may not be the most optimal but I'd like to get it right my way before I attempt any sort of optimizing. I'll include my code below:
class Solution {
public:
vector<int> plusOne(vector<int>& digits)
{
if(digits.at(digits.size()-1) < 9)
{
digits.at(digits.size()-1) += 1;
}
else
{
int zeroCount = 0;
int index = 0;
for(int i = digits.size()-1; i >= 0;--i)
{
if(digits.at(i) == 9)
{
digits.pop_back();
zeroCount++;
}
else
{
index = i;
break;
}
}
if(digits.at(index) < 9)
{
digits.at(index) += 1;
for(int i = 0; i < zeroCount; ++i)
{
digits.push_back(0);
}
}
else
{
digits.push_back(1);
for(int i = 0; i < zeroCount; ++i)
{
digits.push_back(0);
}
}
}
return digits;
}
};
| If all elements are 9, all elements will be removed by this part:
if(digits.at(i) == 9)
{
digits.pop_back();
zeroCount++;
}
Therefore, the condition digits.at(index) < 9 becomes invalid after this operation.
This condition should be !digits.empty() && digits.at(index) < 9 to avoid this error.
|
72,482,793 | 72,485,835 | No matching member function to call for 'push_back' error | While implementing LRU cache got this error.
Earlier I was implementing it via maps it works then but somehow even when doing it as vector it does not work.
#include <list>
class LRUCache {
list<pair<int,int>> lru;
int cap;
vector<list<pair<int, int>>::iterator> hash;
public:
LRUCache(int capacity) {
cap = capacity;
for(int i=0;i<=3000;i++)
hash.push_back(nullptr);
}
int get(int key) {
if(hash[(key)]!=nullptr)
{
int v = hash[key]->first;
lru.erase(hash[key]);
lru.push_front({v,key});
hash[key] = lru.begin();
return v;
}
else
return -1;
}
void put(int key, int value) {
if(hash[(key)]!=nullptr)
{
int v = value;
lru.erase(hash[key]);
lru.push_front({v,key});
hash[key] = lru.begin();
}
else if(lru.size()<cap)
{
lru.push_front({value,key});
hash[key] = lru.begin();
}
else
{
lru.push_front({value,key});
hash[key] = lru.begin();
auto it = lru.end();
it--;
hash[(it->second)] = nullptr;
lru.erase(it);
}
}
};
This way does not work either.
vector<list<pair<int, int>>::iterator> hash(3001,NULL);
Can we not create a vector of pointers?
| Create an iterator variable, instead of nullptr value, as bellow:
list<pair<int, int>>::iterator emptyIt; // this iterator object refer to nothing
// Using `emptyIt` to initialize the hash
LRUCache(int capacity) {
cap = capacity;
for(int i=0;i<=3000;i++)
hash.push_back(emptyIt);
}
// Using emptyIt instead of nullptr
int get(int key) {
if(hash[(key)]!=emptyIt)
{
int v = hash[key]->first;
lru.erase(hash[key]);
lru.push_front({v,key});
hash[key] = lru.begin();
return v;
}
else
return -1;
}
void put(int key, int value) {
if(hash[(key)]!=emptyIt)
{
int v = value;
lru.erase(hash[key]);
lru.push_front({v,key});
hash[key] = lru.begin();
}
else if(lru.size()<cap)
{
lru.push_front({value,key});
hash[key] = lru.begin();
}
else
{
lru.push_front({value,key});
hash[key] = lru.begin();
auto it = lru.end();
it--;
hash[(it->second)] = emptyIt;
lru.erase(it);
}
}
};
|
72,482,815 | 72,623,461 | Deleting all rvalue function overloads of a class | Say I have a class object that must be captured by the caller when returning this class's object from a function call.
// no_can_rvalue *must* be captured
[[nodiscard]] no_can_rvalue a_func();
I can enforce this by deleting all rvalue function overloads, thus making it impossible to use the class functionality unless a caller has captured an object of it (doubled with nodiscard in c++17).
Is it possible to delete all rvalue function overloads of a given class in one fell swoop?
The result being equivalent to :
struct no_can_rvalue {
void f() && = delete;
void f() &;
void g() && = delete;
void g() &;
// etc
};
| No, it is not possible to do so.
|
72,483,524 | 72,483,851 | C++ Error: Continue option is not working and is looping the program instead | Note: I am a beginner in C++, so please bear with me if there are any serious programming errors that can be fixed easily.
Edit: Options 3 and 4 work perfectly fine without any errors. However, Option 2 has a serious looping problem where 'Error! Number should be in range of (1 to 100)' and 'Enter the number again:' loop continuously when you input any key. Will change the code to show the code for Option 2 and remove Option 3 and Option 4's code.
I created a math program that can calculate numbers, calculate fractions, among other features I added. I added a continue button on some programs (Option 2) that when you enter 'Y' on your keyboard, it should loop the program until the user types a different key to signify that the program should stop. However, the continue button seems not to work. When I press any other key, the program still loops and I have to stop the program so it cannot loop.
#include <<iostream>>
#include <<cmath>>
using namespace std;
int main()
{
std::cout << "Math Application Version 0.1 (currently in development)\n";
std::cout << "Choose an application to use (use numbers 1 - 10)\n":
std::cout << "Option 1: Calculator" << std::endl "Option 2: Use Average Calculator" <<
std::endl << "Option 3: Use Fraction Calculator\n" << std::endl <<
"Option 4: Use LCM (Lowest Common Denominator) Calculator\n";
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
// this is blank on purpose because this would get too long if I added more features here
case 2:
{
printf("\n Chose average calculator.");
char d;
int n, i;
float num[100],
sum=0.0,
average;
anon:
{
cout << "Enter the numbers of data (limit is 100) : ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! Number should be in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for (i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
}
cout << "\nDo you want to continue? "; cin >> n;
if (n== 'Y', "Yes")
goto anon;
system("PAUSE");
return 0;
break;
}
I'd appreciate any help on this issue or a detailed explanation since this is very confusing for me.
| Your code is fine but you just have some typos in these lines.
cout << "\nDo you want to continue? ";
cin >> n;
/*Here => */ if (n== 'Y', "Yes")
fix it to if(n == 'Y'), also you have unintentionally used n instead of the char d that you have defined to use as a check.
So your code should be
cout << "\nDo you want to continue? ";
cin >> d;
if (d == 'Y') { .... }
And for completion, avoid goto whenever you can. You can use a while loop instead of the assembly-like goto.
This is your code but with a while loop instead of goto
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
std::cout << "Math Application Version 0.1 (currently in development)\n";
std::cout << "Choose an application to use (use numbers 1 - 10)\n";
std::cout << "Option 1: Calculator" << std::endl << "Option 2: Use Average Calculator" <<
std::endl << "Option 3: Use Fraction Calculator\n" << std::endl <<
"Option 4: Use LCM (Lowest Common Denominator) Calculator\n";
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
// this is blank on purpose because this would get too long if I added more features here
case 2:
printf("\n Chose average calculator.");
char d = 'Y';
int n, i;
float num[100],
sum=0.0,
average;
while (d == 'Y'){
cout << "Enter the numbers of data (limit is 100) : ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! Number should be in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for (i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
cout << "\nDo you want to continue? ";
cin >> d;
}
break;
}
}
|
72,483,808 | 72,484,701 | Default random engine as class member, even if passed by reference does not update external engine | I know that I have to pass the random engine by reference in order for it to update out of a function. However, if I pass it by reference in a class construction, it looks like the seed is not changing outside of the class.
Minimum working example:
#include<iostream>
#include<random>
class rv{
public:
std::default_random_engine rv_eng;
rv(std::default_random_engine & eng){
this->rv_eng = eng;
}
double nd(){
std::normal_distribution<double> ndist {0.0, 1.0};
double draw = ndist(this->rv_eng);
return draw;
}
};
int main(){
std::default_random_engine main_engine;
main_engine.seed(123);
std::cout << main_engine << std::endl;
rv rv_instance(main_engine);
std::cout << rv_instance.nd() << std::endl;
std::cout << main_engine << std::endl;
return 0;
}
The result I get is
123
-0.331232
123
While I would have expected the second generator to change. Why is it the same?
| Like someone else already suggested; use an initializer list, that way you can have a reference variable as a member:
class rv
{
public:
std::default_random_engine& eng_ref;
rv(std::default_random_engine& eng) : eng_ref{ eng } {};
double nd()
{
std::normal_distribution<double> ndist {0.0, 1.0};
double draw = ndist(eng_ref);
return draw;
}
};
|
72,484,378 | 72,484,435 | Function call cannot be matched to a candidate template definition (of a function to receive 2D array by reference) in C++ | Novice here trying a different method to pass array-by-reference in C++.
For C++, geeksforgeeks (under title Template Approach (Reference to Array)) shows a way to pass array by reference in C++ by creating a template. I am trying it because it seems a way to not use pointers and still pass arrays of different sizes on every different function call.
Notice in the following code from geeksforgeeks, a template parameter is specified for the size of the array.
// CPP Program to demonstrate template approach
#include <iostream>
using namespace std;
template <size_t N> void print(int (&a)[N])
{
for (int e : a) {
cout << e << endl;
}
}
// Driver Code
int main()
{
int a[]{ 1, 2, 3, 4, 5 };
print(a);
}
I have tried to extend the logic for 2D arrays by making a a template as followed:
template <size_t r, size_t c>
float approach_mean(vector<int>& n, float (&a)[r][c], float m, float d) {
return 0;
}
class Solution {
public:
int minimumDeviation(vector<int>& nums) {
float m = accumulate(nums.begin(), nums.end(), 0) / nums.size();
float dev = 0, devp = 0;
long double s = 0;
float r[2][nums.size()];
for (int i0 = 0; i0 < nums.size(); ++i0) {
r[0][i0] = nums.at(i0);
r[1][i0] = m - nums.at(i0);
dev = dev + abs(m - nums.at(i0));
}
dev = dev / nums.size();
while (devp < dev) {
devp = dev;
dev = approach_mean(nums, r, m, dev);
break;
}
return devp;
}
// float approach_mean() {
// }
};
Upon running this code, I get an error
Line 21: Char 19: error: no matching function for call to 'approach_mean'
dev = approach_mean(nums, r, m, dev);
^~~~~~~~~~~~~~~
Line 2: Char 7: note: candidate template ignored: could not match 'float' against 'float'
float approach_mean(vector<int>& n, float (&a)[r][c], float m, float d) {
^
1 error generated.
I simply can't think of ways to solve this error. I understand that it is unable to match the return type for some reason even though they are the same.
The entire logic is a WIP for a solution to Problem 1675 on Leetcode which is about reducing the deviation in an array.
Here is a part of the description of the problem:
You are given an array nums of n positive integers.
You can perform two types of operations on any element of the array any number of times:
If the element is even, divide it by 2.
For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
If the element is odd, multiply it by 2.
For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].
The deviation of the array is the maximum difference between any two elements in the array.
Return the minimum deviation the array can have after performing some number of operations.
| The problem is that float r[2][nums.size()]; is not standard C++ as the size of an array must be a compile time constant.
But as nums.size() is not a constant expression so it cannot be used to specify the size of an array and moreover it cannot be used as a template nontype argument as a template nontype argument must be a compile time constant.
You can verify this by changing nums.size() with some constant expression in float r[2][nums.size()]; and you will find out that the mentioned error is gone.
//-----------------v------>nums.size() replaced with 5
float r[2][5];
Demo with no compile time error
|
72,484,487 | 72,484,599 | C++ Library management system | I'm doing a library management system using arrays as database, when I enter a value in bookName, and after a loop and enter a value again, when I print all values in bookName[], it only prints the last value I entered. Please help me!!
Heres my code:
#include<iostream>
using namespace std;
int main(){
char yesNo;
string bookName[50];
string bookAuthor[50];
string bookID[50];
int i, choice;
do{
cout << "==========================" << endl;
cout << "LIBRARY MANAGEMENT SYSTEM" << endl;
cout << "==========================" << endl;
cout << "[1] Add Books" << endl;
cout << "[2] Delete Books" << endl;
cout << "[3] Search Books" << endl;
cout << "[4] View Book List" << endl;
cout << "[5] Close Application" << endl;
cout<<"Enter a number: ";
cin>>choice;
switch(choice){
case 1:
cin.ignore();
cout<<"Enter book name: ";
for(i=0; i<10; i++){
getline(cin, bookName[i]);
break;}
cout<<"Enter book author: ";
getline(cin, bookAuthor[i]);
cout<<"Enter book ID: ";
getline(cin, bookID[i]);
cout<<"Book succesfully added!"<<endl;
break;
case 4:
cout<<"All Books"<<endl;
for(int x=0; x<=i; x++){
cout<< bookName[x];
}
}
cout<<"Do you want to continue (Y/N)";
cin>>yesNo;
}while (yesNo == 'y' || yesNo == 'Y');
cout<<"Thank You!";
return 0;
}
| The for loop in your code initializes the variable i to zero, everytime you want to add a new book. Inside the for loop there is a break that exits the for loop after entering the string describing the book name.
When the user selects option 4, the variable i will always be zero. Therefore, you will only print the info of the last book you entered. For completeness, every book you enter will always be stored at index 0 (replacing the previous entry).
The following fixes your problem - quick and dirty. However, you might want to re-design your code:
#include<iostream>
using namespace std;
int main(){
char yesNo;
string bookName[50];
string bookAuthor[50];
string bookID[50];
int i = 0, choice; // Important! You need to initialize the
// variable i since this is going to be used
// as index to access the array!
do
{
cout << "==========================" << endl;
cout << "LIBRARY MANAGEMENT SYSTEM" << endl;
cout << "==========================" << endl;
cout << "[1] Add Books" << endl;
cout << "[2] Delete Books" << endl;
cout << "[3] Search Books" << endl;
cout << "[4] View Book List" << endl;
cout << "[5] Close Application" << endl;
cout<<"Enter a number: ";
cin>>choice;
switch(choice)
{
case 1:
cin.ignore();
cout<<"Enter book name: ";
getline(cin, bookName[i]);
cout<<"Enter book author: ";
getline(cin, bookAuthor[i]);
cout<<"Enter book ID: ";
getline(cin, bookID[i]);
i++; // Increment i. Check here that you don't go above 50
cout<<"Book succesfully added!"<<endl;
break;
case 4:
cout<<"All Books"<<endl;
for(int x=0; x<i; x++) // C/C++ start from 0. So the loop needs to end when index is i-1
{
cout<< bookName[x] << endl;
}
}
cout<<"Do you want to continue (Y/N)";
cin>>yesNo;
}while (yesNo == 'y' || yesNo == 'Y');
cout<<"Thank You!";
return 0;
}
You can see a running version here: https://onlinegdb.com/TNUn3jpyM
|
72,484,813 | 72,506,552 | Declare a class and member variables using macros in C++ | I would like to use preprocessor macros to declare many classes like the following:
class ClassA : public ClassBase
{
public:
int a;
float b;
char c;
std::vector<void *> fun()
{
/*
Code that uses all member variables
*/
std::vector<void *> v{&a, &b, &c};
return v;
}
};
For example, the same class declared with macros may look something like this:
BEGIN_CLASS(ClassA)
MEMBER(int, a)
MEMBER(float, b)
MEMBER(char, c)
END_CLASS(ClassA)
or (@Peter, thanks for ruling out above option)
NEW_CLASS(ClassA, int, a, float, b, char, c)
The only parts of the declaration that will change are class name, member variable names, member variable type and number of member variables. Everything else will follow the same template.
In my application, users will need to declare classes like this regularly and I would like to provide a simpler interface for them.
Regardless of whether this is good practice, I'd like to know if declaring a class like this is possible and if so, how?
| #define NEW_CLASS(name_, seq_) \
class name_ : public ClassBase \
{ \
public: \
IMPL_NEW_CLASS_end(IMPL_NEW_CLASS_decl_loop_a seq_)\
\
std::vector<void *> fun() \
{ \
return { IMPL_NEW_CLASS_end(IMPL_NEW_CLASS_list_loop_a seq_) }; \
} \
};
#define IMPL_NEW_CLASS_end(...) IMPL_NEW_CLASS_end_(__VA_ARGS__)
#define IMPL_NEW_CLASS_end_(...) __VA_ARGS__##_end
#define IMPL_NEW_CLASS_decl_loop_a(...) ::std::type_identity_t<__VA_ARGS__> IMPL_NEW_CLASS_decl_loop_b
#define IMPL_NEW_CLASS_decl_loop_b(name_) name_; IMPL_NEW_CLASS_decl_loop_a
#define IMPL_NEW_CLASS_decl_loop_a_end
#define IMPL_NEW_CLASS_list_loop_a(...) IMPL_NEW_CLASS_list_loop_b
#define IMPL_NEW_CLASS_list_loop_b(name_) &name_, IMPL_NEW_CLASS_list_loop_a
#define IMPL_NEW_CLASS_list_loop_a_end
NEW_CLASS(ClassA, (int)(a) (float)(b) (char)(c))
I've used the (a)(b)(c) syntax for lists, because AFAIK only those lists can be traversed without generating a bunch of repetitive boilerplate macros. (can't do that with a, b, c)
I've wrapped the type in std::type_identity_t<...> to allow arrays, function pointers, etc (int[4] x; is invalid, but std::type_identity_t<int[4]> x; is ok).
I chose this specific syntax because the types can contain commas, so e.g. (type,name)(type,name) wouldn't be viable, because it's tricky to extract the last element from a comma-separated list (consider (std::map<int,float>,x), which counts as a comma-separated list with 3 elements).
(name,type)(name,type), on the other hand, would be viable (extracting the first element of a list is simple), but it doesn't look as good. If you go for this syntax, note that the loops still have to use at least two macros each (_a and _b in my example), even if the two would be the same (a single-macro loop doesn't work because of the ban on recursive macros). The loops would also need two _end macros each, not one.
|
72,485,369 | 72,485,543 | Calling constructor with string argument passing char * report error | template<typename T>
class SharedValue {
public:
SharedValue(const T& t): valuePtr(new T(t)) {}
const SharedValue& operator = (const T &t) {
*valuePtr = t;
return *this;
}
protected:
dd_shared_ptr<T> valuePtr;
};
typedef SharedValue<std::string> SharedString;
int main(int argc, const char * argv[]) {
// compile succeeded
SharedString str(argv[0]);
// compile failed:
SharedString str2 = argv[0];
return 0;
}
The str2 construction failed, reporting:
No viable conversion from 'const char *' to 'SharedString' (aka 'SharedValue<basic_string<char, char_traits<char>, allocator<char>>>')
Why str succeeded whereas str2 failed, is there any difference?
|
Why str succeeded whereas str2 failed, is there any difference?
Yes, there is difference between the two. In particular, in str we have have direct initialization while in str2 we have copy initialization.
The behavior of your program can be understood from copy initialization documentation which states:
In addition, the implicit conversion in copy-initialization must produce T directly from the initializer, while, e.g. direct-initialization expects an implicit conversion from the initializer to an argument of T's constructor.
(emphasis mine)
Now let's apply this to your given example on case by case basis.
Case 1
Here we consider the statement:
SharedString str2 = argv[0]; //this is copy initialization
The above uses copy initialization. And as SharedString can't be directly produced from the initializer of type const char* on the right hand side since it requires an implicit conversion, this case 1 isn't allowed in accordance with the above quoted statement.
Case 2
Here we consider the statement:
SharedString str(argv[0]); //this is direct initialization
while the above uses direct initialization and since there is an implicit conversion available(using the converting constructor), this time it is allowed according to the above quoted statement.
|
72,486,352 | 72,534,617 | Implicit object parameter C++ | In this link : Implicit object parameter
In this quote :
If any candidate function is a member function (static or non-static) that does not have an explicit object parameter (since C++23), but not a constructor, it is treated as if it has an extra parameter (implicit object parameter) which represents the object for which they are called and appears before the first of the actual parameters.
I do not understand why the word static is mentioned here? Isn't the implicit object parameter the this pointer ( which only exists in non-static functions ) ?
Edit
in this link : link
quote :
The keyword this is a rvalue (until C++11)prvalue (since C++11) expression whose value is the address of the implicit object parameter (object on which the non-static member function is being called). It can appear in the following contexts:
| It's useful to consider examples. When you have:
struct C {
void f(int);
void f(int) const;
};
C c;
c.f(42);
How does overload resolution pick? You effectively have a choice of:
// implicit object | regular
// parameter | parameter
void f(C&, int );
void f(C const&, int );
With the arguments (C, int). That ends up picking the first one, for being a better match.
Now, let's think of this example:
struct D {
static void g(int);
void g(long);
};
D d;
d.g(42);
Now, if we try to do the same thing:
// implicit object | regular
// parameter | parameter
void g(????????, int );
void g(D&, long );
We have two arguments, a D and an int. We don't know if we're going to call a static function or not yet, we still have to do overload resolution. How do we pick in this case? The non-static member function has an implicit object parameter, D&, but what do we do for the static one?
The C++ answer is we contrive a fake parameter, that is a perfect match for everything:
// implicit object | regular
// parameter | parameter
void g(contrived-match, int );
void g(D&, long );
And now, when we do overload resolution with (D, int), you can see that the static function is the best match (better conversion sequence for the second parameter).
Once we pick the static member function, we then ignore the object argument entirely. d.f(42) basically evaluates as D::f(42). But we didn't know that until we performed overload resolution - the contrived parameter exists to solve the problem of how to actually compare these cases.
This still applies even if there were just the one static member function - since d.f(42) does have two parameters: the d and the 42, so the language needs to handle the d somehow (the alternative could've been to simply disallow this syntax, requiring D::f(42) if you wanted to call a static member function, but that seems a lot less nice).
|
72,486,990 | 72,488,664 | Why thread_local in different compiler or different platform has the different outcome? | #include <iostream>
#include <unordered_map>
#include <vector>
#include <thread>
using namespace std;
// not POD
struct A {
std::unordered_map<int, int> m_test;
};
struct B{
thread_local static A a;
};
thread_local A B::a = A();
B b;
void func(){
b.a.m_test[0]++;
}
int main() {
vector<thread> Threads;
for (int i = 0; i < 10; i++) {
Threads.push_back(thread(func));
}
for (int i = 0; i < 10; i++) {
Threads[i].join();
}
return 0;
}
the code snippet is showed as above.
I built the same code in Linux: gcc 4.8.5 and MacOS:clang13.1.6 , outcome is the different . In Linux, An error occurred as 17703 Floating point exception(core dumped), but in MacOS there was no error occurred.
I know thread_local can use in POD type after c++11, but here I use the unordered_map in struct, which internal memory is in the heap, not in the static or global storage area. So I wonder if this is because of how different compilers implement the C++ standard?
And how can I solve this runtime error on the linux platform?
| Based on testing on compiler explorer, this seems to be a GCC bug fixed in 2019 for versions 9+, 8.4+ and 7.5+. The code should work fine as posted. There is nothing wrong with it.
Probably it is this bug.
I recommend you install and use a more up-to-date version of GCC.
|
72,487,498 | 72,499,990 | How Rvalue references bind to a temporary value (rvalue) behind the hood | I am interested in how the following code:
int&& c = 2;
c++;
std::cout << c; //3
keeps the variable 'c' in memory?
How the compiler implements the reference at the machine level? Does it set aside any memory for it? If so, where? Or it keeps it in CPU register?
| Whether or not a reference is bound to a lifetime-extended temporary is a property that is determined at compile-time for the specific reference.
For example in
{
int x = 2;
int&& c = std::move(x);
c++;
std::cout << c; //3
}
the value category of std::move(x) is xvalue and therefore it doesn't result in the creation of a temporary whose lifetime would be extended.
On the other hand in
{
int&& c = 2;
c++;
std::cout << c; //3
}
the initializer expression 2 is a prvalue. A prvalue needs to be materialized into a temporary to which the reference can bind. Because the materialization happens directly before binding the reference, the lifetime of the temporary is extended to match that of the reference.
Effectively, the two snippets do the same thing and the compiler can simply transform the second one into the first one. Consequently the usual rules for storage of objects apply. The int object (either the variable or the temporary) will typically be stored on the stack or in a register depending on whether the compiler will end up needing it to have an address. The reference is typically implemented similar to a pointer, also on the stack or in a register.
However, in such a simple example, the compiler doesn't need to store the reference at all, since it knows where the variable or temporary which the reference references is stored in the function. In machine instructions all uses of the reference can simply be replaced with memory or register references to the object.
Practically speaking the snippet will then be equivalent to
{
int c = 2;
c++;
std::cout << c; //3
}
Furthermore, usual optimizations apply and the compiler will in the case in your question simply do constant-propagation and see that you are just outputting the same number all the time. Instead of storing either the variable or the reference, it can just optimize the whole thing to std::cout << 3;.
|
72,487,682 | 72,487,986 | Why getting reference binding to null-pointer error? | I am solving the following Leetcode problem:
https://leetcode.com/problems/find-if-path-exists-in-graph/
I am getting the following error:
Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator<int>>' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
The code for my approach:
class Solution {
public:
void dfs(int *visited,int node,vector<vector<int>>&adj)
{
visited[node]=1;
for(auto child:adj[node])
{
if(visited[child]==-1)
dfs(visited,child,adj);
}
}
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>>adj;
for(auto it:edges)
{
adj[it[0]].push_back(it[1]);
}
int visited[n];
for(int i=0;i<n;i++)
visited[i]=-1;
dfs(visited,source,adj);
return visited[destination]==1;
}
};
I'm getting this error for almost every graph problem. Can someone point out the mistake?
| The outer vector of adj should be resized, before adding elements to the inner vector.
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<vector<int>>adj;
for(auto& it:edges)
{
if (adj.size() < (it[0] + 1))
{
adj.resize(it[0] + 1);
}
adj[it[0]].push_back(it[1]);
}
//Rest of the code
}
|
72,488,154 | 72,503,232 | MacOS C++ SFML Failed to add a new character to the font: the maximum texture size has been reached | I'm trying to write "hello world" to an SFML window... i know
If I paste SFML font/text tutorial code in GSpace class, I get the error: "Failed to add a new character to the font: the maximum texture size has been reached"
If I comment all of that out, and copy/paste to Simpulator class it works. If I undo everything, it works. If I copy what just worked into a new sf::Text in GSpace class: "Failed to add.." If I comment out "setStyle" I get "Segmentation fault: 11."
I'm using an old mac version 10.14.6.. I can't use XCode because my computer's so old it won't update, setting up other IDEs seemed as complicated as not using them, so I'm just using the terminal with a makefile.
I know next to nothing about makefiles and compilers. I copied most of what I have just to get things up and running.. It seems like something happens when compiling the Simpulator class, that doesn't happen when compiling the Menu class. Whatever happens when Simpulator is compiled might persist even after changing everything back, so the variables in GSpace suddenly function properly? ..that seems like an error.
Because it's the thing I least understand and, in my mind, the thing most prone to failure, here is my makefile:
SFML_LIB = -I..SFML/lib
SFML_INCLUDE = -I..SFML/include
SFML_FRAMEWORKS = -I..SFML/Frameworks
LIBS= -lsfml-graphics -lsfml-window -lsfml-system -lsfml-audio -lsfml-network
CXX = clang++
CXXFLAGS = -std=c++11
Simpulator: main.o Simpulator.o GameSpace.o
$(CXX) $(CXXFLAGS) main.o Simpulator.o GameSpace.o -o Simpulator $(LIBS)
main.o: main.cpp
$(CXX) $(CXXFLAGS) -c $<
Simpulator.o: Source/Simpulator.cpp Header/Simpulator.h
$(CXX) $(CXXFLAGS) -c $<
GameSpace.o: Source/GameSpace.cpp Header/GameSpace.h
$(CXX) $(CXXFLAGS) -c $<
clean:
rm *.o Simpulator
Let me know if I should provide additional code.
Thanks for any help!
EDIT:
I've used both Arial.ttf and Tahoma.ttf fonts. The code I'm using is copy/paste from SFML site. This is the declaration in the class header:
sf::Font font;
sf::Text text;
This is in a "load" function:
if (!font.loadFromFile("Arial.ttf"))
{
// error...
}
// select the font
text.setFont(font); // font is a sf::Font
// set the string to display
text.setString("Hello world");
// set the character size
text.setCharacterSize(24); // in pixels, not points!
// set the color
text.setFillColor(sf::Color::Red);
// set the text style
text.setStyle(sf::Text::Bold | sf::Text::Underlined);
If I write this in GSpace, it doesn't work. If I remove it and copy to Simpulator, it works. If I remove it from Simpulator and copy back to GSpace, it works.
EDIT:
I found that as long as Simpulator.cpp is updated and recompiled, I can add a new sf::Text to GSpace with no errors. So if after adding sf::Text code to GSpace, I add "asdf" to Simpulator.cpp, save it, remove it, then save it again, there are no errors.
| I edited the make file from:
Simpulator.o: Source/Simpulator.cpp Header/Simpulator.h
$(CXX) $(CXXFLAGS) -c $<
to:
Simpulator.o: Source/Simpulator.cpp Header/Simpulator.h Header/GSpace.h
$(CXX) $(CXXFLAGS) -c $<
|
72,488,691 | 72,488,807 | Resolve enum class variable name to string | Consider, I have got the following enum class:
enum class TestEnum
{
None = 0,
Foo,
Bar
};
I'd like to specify ostream operator ( << ) for this enum class, so I could write:
std::cout << "This is " << TestEnum::Foo;
and get following output This is Foo.
My question is:
Is there any place where enum "name specifiers" are stored? (i.e. for enum class TestEnum it is None, Foo and Bar) So I could write a function (or at best function template) that specifies ostream operator for this TestEnum like:
std::ostream& operator<< ( std::ostream& os, TestEnum aEnum ) {
return std::string( aEnum.name() );
}
So far, I did it this way:
std::ostream& operator<< ( std::ostream& os, TestEnum aEnum ) {
switch( aEnum )
{
case TestEnum::Foo:
os << "Foo";
break;
case TestEnum::Bar:
os << "Bar"
break;
}
return os;
}
I have seen some solutions using boost library, but I would prefer not using it this time.
|
Is there any place where enum "name specifiers" are stored?
No, but one option is to use std::map<TestEnum, std::string> as shown below:
enum class TestEnum
{
None = 0,
Foo,
Bar
};
const std::map<TestEnum,std::string> myMap{{TestEnum::None, "None"},
{TestEnum::Foo, "Foo"},
{TestEnum::Bar, "Bar"}};
std::ostream& operator<< ( std::ostream& os, TestEnum aEnum )
{
os << myMap.at(aEnum);
return os;
}
int main()
{
std::cout << "This is " << TestEnum::Foo; //prints This is Foo
std::cout << "This is " << TestEnum::Bar; //prints This is Bar
return 0;
}
Demo
|
72,488,935 | 74,487,496 | Conditional inheritance based on derived type | I have a set of graph classes that can be composed to create directed graphs for different purposes. For instance, it can be a plain directed graph, or functionality for traversal or nested graphs can be added.
TraversableGraph and TraversableNode should inherit a StatusTrait. However, if the TraversableGraph is also a NestedGraph, only TraversableNode should inherit the StatusTrait. The reason is that NestedGraph inherits from the derived node (which inherits from TraversableNode), and I don't want to run into the diamond problem.
My idea is to make the inheritance of StatusTrait conditional for TraversableGraph: Only inherit if the derived class is not a NestedGraph.
Here is my attempt:
#include <type_traits>
// Status trait
// This should be part of traversable nodes and graphs.
// If a traversable graph is also a nested graph, the status trait should not
// become part of the graph, as it is already part of the traversable node
// inherited by the nested graph.
template<class DerivedClass>
class StatusTrait {
public:
auto Status() const -> int { return 0; }
};
class EmptyTrait {};
// Directed graph
class Node {};
class Graph {};
// Nested graph
template<class BaseClass>
class NestedNode
: public BaseClass
{};
template<class BaseClass, class NodeClass>
class NestedGraph
: public BaseClass
, public NodeClass // Nested graphs are also nodes.
{};
// For checking if a graph is a nested graph compile-time.
template<class BaseClass, class NodeClass>
std::true_type IsNestedGraph(NestedGraph<BaseClass, NodeClass> const *);
std::false_type IsNestedGraph(...);
// Traversable graph
template<class BaseClass>
class TraversableNode
: public BaseClass
, public StatusTrait<TraversableNode<BaseClass>>
{};
template<class BaseClass, class DerivedClass>
class TraversableGraph
: public BaseClass
// If the derived class is a nested graph, don't inherit the status trait.
, public std::conditional_t<decltype(IsNestedGraph(std::declval<typename DerivedClass *>()))::value, EmptyTrait, StatusTrait<DerivedClass>>
{};
int main() {
class MyTraversableNode: public TraversableNode<Node> {};
class MyTraversableGraph: public TraversableGraph<Graph, MyTraversableGraph> {};
MyTraversableNode TN;
MyTraversableGraph TG;
TN.Status();
TG.Status();
class MyNestedTraversableNode: public NestedNode<TraversableNode<Node>> {};
class MyNestedTraversableGraph: public NestedGraph<TraversableGraph<Graph, MyNestedTraversableGraph>, MyNestedTraversableNode> {};
MyNestedTraversableNode NTN;
MyNestedTraversableGraph NTG;
NTN.Status();
NTG.Status(); // Ambiguous access, since the status trait is part of both traversable graph and traversable node.
class MyTraversableNestedNode: public TraversableNode<NestedNode<Node>> {};
class MyTraversableNestedGraph: public TraversableGraph<NestedGraph<Graph, MyTraversableNestedNode>, MyTraversableNestedGraph> {};
MyTraversableNestedNode TNN;
MyTraversableNestedGraph TNG;
TNN.Status();
TNG.Status(); // Ambiguous access, since the status trait is part of both traversable graph and traversable node.
return 0;
}
The code does not compile, but complains that NTG.Status() and TNG.Status() is ambiguous. This indicates that TraversableGraph inherits StatusTrait even when the derived class is a NestedGraph.
If I change the condition to check whether the base class is a NestedGraph instead of checking the derived class, the compiler only complains about NTG.Status() being ambiguous.
std::conditional_t<decltype(IsNestedGraph(std::declval<typename BaseClass *>()))::value, EmptyTrait, StatusTrait<DerivedClass>>`
So my code is able to determine whether the base class is a NestedGraph, but not whether the derived class is one. How can I fix this?
Here is an interactive editor where you can play with the code: https://godbolt.org/z/1h4153E1n
| I've finally found the solution!
As pointed out by @Jarod42, checking whether the derived class is a NestedGraph is not possible, since the derived class is incomplete when checking. Instead we can check whether the derived node is a NestedNode! We just need to pass the derived node as a template parameter to TraversableGraph, and the rest is easy :)
#include <type_traits>
// Status trait
// This should be part of traversable nodes and graphs.
// If a traversable graph is also a nested graph, the status trait should not
// become part of the graph, as it is already part of the traversable node
// inherited by the nested graph.
class StatusTrait {
public:
auto Status() const -> int { return 0; }
};
// Directed graph
class Node {};
class Graph {};
// Nested graph
template<class BaseClass>
class NestedNode
: public BaseClass
{};
template<class BaseClass, class NodeClass>
class NestedGraph
: public BaseClass
, public NodeClass // Nested graphs are also nodes.
{};
// For checking if a node is a nested node compile-time.
template<class BaseClass>
std::true_type IsNestedNode(NestedNode<BaseClass> const *);
std::false_type IsNestedNode(...);
// Traversable graph
template<class BaseClass>
class TraversableNode
: public BaseClass
, public StatusTrait
{};
template<class BaseClass, class DerivedClass, class DerivedNode>
class TraversableGraph
: public BaseClass
// If the derived class is a nested graph, don't inherit the status trait.
, public std::conditional_t<decltype(IsNestedNode(std::declval<typename DerivedNode *>()))::value, void, StatusTrait>
{};
int main() {
class MyTraversableNode: public TraversableNode<Node> {};
class MyTraversableGraph: public TraversableGraph<Graph, MyTraversableGraph, MyTraversableNode> {};
MyTraversableNode TN;
MyTraversableGraph TG;
TN.Status();
TG.Status();
class MyNestedTraversableNode: public NestedNode<TraversableNode<Node>> {};
class MyNestedTraversableGraph: public NestedGraph<TraversableGraph<Graph, MyNestedTraversableGraph, MyNestedTraversableNode>, MyNestedTraversableNode> {};
MyNestedTraversableNode NTN;
MyNestedTraversableGraph NTG;
NTN.Status();
NTG.Status(); // Works.
class MyTraversableNestedNode: public TraversableNode<NestedNode<Node>> {};
class MyTraversableNestedGraph: public TraversableGraph<NestedGraph<Graph, MyTraversableNestedNode>, MyTraversableNestedGraph, MyTraversableNestedNode> {};
MyTraversableNestedNode TNN;
MyTraversableNestedGraph TNG;
TNN.Status();
TNG.Status(); // Works.
return 0;
}
|
72,489,726 | 72,490,130 | Switch Case with While Loop in C++ Menu | I've been building a menu driven console in C++, and I'm currently using switch-case as my options, but now I'm stuck in switch case.
Here's the scenario:
SCENARIO
Explanation:
After inputting invalid option in the main menu, it gives an error which prompts the user to re-input their desired option, now my problem is when the user inputs the correct option for the 2nd attempt, it loops back to the main menu instead of redirecting it to the next menu.
My Goal: To go to the 2nd menu directly from the default without redisplaying the main menu.
My Partial Code:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int choice;
int booknumber;
int booktitle;
int author;
int datepublished;
int e = 0;
void menu();
void inputbook();
void searchbook();
void borrowbook();
void exit();
//CLASS
class Books
{
public:
int booknumber;
string booktitle;
string author;
string datepublished;
Books(const int booknumber, const string booktitle, const string author, const string datepublished) : booknumber(booknumber), booktitle(booktitle), author(author), datepublished(datepublished) {}
};
//MAIN
int main()
{
while (true)
{
cout << endl;
if (e == 1)
{
break;
}
menu ();
}
return 0;
}
//MENU
void menu()
{
cout << "Welcome to DLC Library System\n";
cout << "Final Project in Advance Programming\n\n";
cout << "PROGRAMMER\n";
cout << "ME\n\n";
cout << "====================================\n";
cout << "[1] -------- Input Book ------------\n";
cout << "[2] -------- Search Book -----------\n";
cout << "[3] -------- Borrow Book -----------\n";
cout << "[4] -------- Exit Program ----------\n";
cout << "====================================\n";
cout << "Input your choice (Number Only): ";
cin >> choice;
switch (choice)
{
case 1:
inputbook ();
break;
case 2:
searchbook ();
break;
case 3:
borrowbook ();
break;
case 4:
exit();
break;
default:
while (choice < 1 || choice > 4)
{
cout << "Wrong Option\n";
cout << "Input your choice (Number Only): ";
cin >> choice;
if (choice < 1 || choice > 4)
{
continue;
}
}
}
}
// INPUT BOOK
void inputbook ()
{
int booknumber;
string booktitle;
string author;
string datepublished;
cout << "INPUT NEW BOOK\n\n";
cout << "Book Number: \n";
cin >> booknumber;
cout << "Book Title: \n";
cin >> booktitle;
cout << "Author: \n";
cin >> author;
cout << "Date Publish: \n";
cin >> datepublished;
Books(booknumber,booktitle, author, datepublished);
cout << "====================================\n";
cout << "[1] -------- Try Again? ------------\n";
cout << "[2] -------- Return to Menu --------\n";
cout << "[3] -------- Exit Program ----------\n";
cout << "====================================\n";
cout << "Input your choice (Number Only): ";
cin >> choice;
switch (choice)
{
case 1:
inputbook ();
break;
case 2:
menu ();
break;
case 3:
exit();
default:
cout << "Wrong Option";
}
}
| It's a good idea to avoid repeating code. Here, you have a default case that is essentially an input loop, whereas you could have done that input loop at the start. So the way you wrote it, you still need a loop around the whole thing, plus more logic which makes the code harder to read and more bug-prone.
Why not simply:
cout << "====================================\n";
cout << "[1] -------- Input Book ------------\n";
cout << "[2] -------- Search Book -----------\n";
cout << "[3] -------- Borrow Book -----------\n";
cout << "[4] -------- Exit Program ----------\n";
cout << "====================================\n";
int choice;
bool validInput = false;
while (!validInput)
{
cout << "Input your choice (Number Only): ";
if (!(cin >> choice)) {
std::cerr << "Aborted\n";
return;
}
validInput = (choice >= 1 && choice <= 4);
if (!validInput) {
std::cout << "Invalid input\n";
}
}
switch(choice)
{
// ...
}
Now it's up to you to make your input routine more robust if you choose. Notice I've already bailed out of the function if the input fails. That could be from a stream error, but it could also be if the user enters a non-integer value.
You may instead wish to read your input as a string using std::getline and then convert that to an integer with std::stoi or parse the value from a std::istringstream.
|
72,490,604 | 72,513,816 | pointer already defined in file | I have this piece of code that works as expected when all of it is in a single file
The problem is i need the platform to have a static pointer to the engine and vice versa
#include <iostream>
#pragma region include/iplatform.h
namespace engine {
class IEngine;
}
namespace platform {
class IPlatform {
public:
virtual ~IPlatform() = default;
static engine::IEngine* ptrEngine;
};
static std::unique_ptr<IPlatform> platform;
engine::IEngine* platform::IPlatform::ptrEngine = nullptr;
}
#pragma endregion
#pragma region include/iengine.h
namespace engine {
class IEngine {
};
}
#pragma endregion
#pragma region include/engine.h
namespace engine {
class Engine : public IEngine {
public:
Engine();
void setup();
};
}
#pragma endregion
#pragma region src/enginge.cpp
namespace engine {
Engine::Engine() { setup(); }
}
#pragma endregion
#pragma region include/platform.h
namespace platform {
class Platform : public platform::IPlatform{
public:
virtual ~Platform() override;
};
}
#pragma endregion
#pragma region src/platform.cpp
namespace platform {
Platform::~Platform() {
}
}
#pragma endregion
#pragma region src/engine.cpp
namespace engine {
void Engine::setup() {
platform::platform = std::make_unique<platform::Platform>();
platform::platform->ptrEngine = this;
}
}
#pragma endregion
int main() {
engine::Engine* e = new engine::Engine();
std::cout << "" << e << std::endl;
std::cout << "" << platform::platform->ptrEngine;
return 0;
}
but once i separate it out into files as outlined by the region blocks i start getting errors, the project structure requires us to have headers and source separately
Severity Code Description Project File Line Suppression State
Warning C6031 Return value ignored: 'std::unique_ptr<platform::IPlatform,std::default_delete<platform::IPlatform> >::->'. CPP_BOILERPLATE C:\Users\Tiit\Documents\cpp\cpp-project-masters\app\main.cpp 74
Warning C6031 Return value ignored: 'std::unique_ptr<platform::IPlatform,std::default_delete<platform::IPlatform> >::->'. CPP_BOILERPLATE C:\Users\Tiit\Documents\cpp\cpp-project-masters\app\main.cpp 83
Warning D9025 overriding '/W3' with '/W4' C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cpp-project-masters C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cl 1
Warning D9025 overriding '/W3' with '/W4' C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cpp-project-masters C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cl 1
Error LNK2005 "public: static class engine::IEngine * platform::IPlatform::ptrEngine" (?ptrEngine@IPlatform@platform@@2PEAVIEngine@engine@@EA) already defined in engine.cpp.obj C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cpp-project-masters C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\platform.cpp.obj 1
Error LNK1169 one or more multiply defined symbols found C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\cpp-project-masters C:\Users\Tiit\Documents\cpp\cpp-project-masters\out\build\x64-Debug\main.exe 1
is there a way to do this
| The solution as @wohlstad commented was moving the line
engine::IEngine* platform::IPlatform::ptrEngine = nullptr;
to one of the source files
|
72,490,616 | 72,500,328 | Processing flutter images with C++ openCV | I am working on a project, where I want to process my images using C++ OpenCV.
For simplicity's sake, I just want to convert Uint8List to cv::Mat and back.
Following this tutorial, I managed to make a pipeline that doesn't crash the app. Specifically:
I created a function in a .cpp that takes the pointer to my Uint8List, rawBytes, and encodes it as a .jpg:
int encodeIm(int h, int w, uchar *rawBytes, uchar **encodedOutput) {
cv::Mat img = cv::Mat(h, w, CV_8UC3, rawBytes); //CV_8UC3
vector<uchar> buf;
cv:imencode(".jpg", img, buf); // save output into buf. Note that Dart Image.memory can process either .png or .jpg, which is why we're doing this encoding
*encodedOutput = (unsigned char *) malloc(buf.size());
for (int i=0; i < buf.size(); i++)
(*encodedOutput)[i] = buf[i];
return (int) buf.size();
}
Then I wrote a function in a .dart that calls my c++ encodeIm(int h, int w, uchar *rawBytes, uchar **encodedOutput):
//allocate memory heap for the image
Pointer<Uint8> imgPtr = malloc.allocate(imgBytes.lengthInBytes);
//allocate just 8 bytes to store a pointer that will be malloced in C++ that points to our variably sized encoded image
Pointer<Pointer<Uint8>> encodedImgPtr = malloc.allocate(8);
//copy the image data into the memory heap we just allocated
imgPtr.asTypedList(imgBytes.length).setAll(0, imgBytes);
//c++ image processing
//image in memory heap -> processing... -> processed image in memory heap
int encodedImgLen = _encodeIm(height, width, imgPtr, encodedImgPtr);
//
//retrieve the image data from the memory heap
Pointer<Uint8> cppPointer = encodedImgPtr.elementAt(0).value;
Uint8List encodedImBytes = cppPointer.asTypedList(encodedImgLen);
//myImg = Image.memory(encodedImBytes);
return encodedImBytes;
//free memory heap
//malloc.free(imgPtr);
//malloc.free(cppPointer);
//malloc.free(encodedImgPtr); // always frees 8 bytes
}
Then I linked c++ with dart via:
final DynamicLibrary nativeLib = Platform.isAndroid
? DynamicLibrary.open("libnative_opencv.so")
: DynamicLibrary.process();
final int Function(int height, int width, Pointer<Uint8> bytes, Pointer<Pointer<Uint8>> encodedOutput)
_encodeIm = nativeLib
.lookup<NativeFunction<Int32 Function(Int32 height, Int32 width,
Pointer<Uint8> bytes, Pointer<Pointer<Uint8>> encodedOutput)>>('encodeIm').asFunction();
And finally I show the result in Flutter via:
Image.memory(...)
Now, the pipeline doesn't crash, which means I haven't goofed up memory handling completely, but it doesn't return the original image either, which means I did mess up somewhere.
Original image:
Pipeline output:
| Thanks to Richard Heap's guidance in the comments, I managed to fix the pipeline by changing my matrix definition from
cv::Mat img = cv::Mat(h, w, CV_8UC3, rawBytes);
to
vector<uint8_t> buffer(rawBytes, rawBytes + inBytesCount);
Mat img = imdecode(buffer, IMREAD_COLOR);
where inBytesCount is the length of imgBytes.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.