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
|
|---|---|---|---|---|
74,431,194
| 74,433,643
|
Wierd stuff happens when overloading operator<< with a class template
|
Here's the functionality I am expecting to achieve:
darray<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
std::cout << a << std::endl; // displays: {1, 2, 3}
My implementation:
template <typename T>
class darray
{
private:
long m_capacity;
long m_size;
T* m_data;
void resize();
public:
// constructors & destructors
darray();
// operations
void push_back(T);
std::ostream& print(std::ostream&) const;
template<typename U> friend std::ostream& operator<<(std::ostream& os, U const& ar);
};
template<typename T>
std::ostream& darray<T>::print(std::ostream& os) const
{
os << "{ ";
for (size_t i = 0; i < m_size; i++)
{
os << m_data[i] << ", ";
if ( i == m_size - 1 )
os << m_data[i];
}
os << " }\n";
return arr;
}
template<typename U>
std::ostream& operator<<(std::ostream& os, U const& obj)
{
return obj.print(os);
}
produces an error:
error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘const char [66]’)
But, when I change the parameter of operator<< to accept a darray<U> instead , it works fine:
template<typename U>
std::ostream& operator<<(std::ostream& os, darray<U> const& obj)
{
return obj.print(os);
}
What am I missing here?
Update:
I also tried doing this, changing the parameter to darray<U> type in the definition and the implementation, but it still produces the same error:
template <typename T>
class darray
{
private:
long m_capacity;
long m_size;
T* m_data;
void resize();
public:
// constructors & destructors
darray();
// operations
void push_back(T);
std::ostream& print(std::ostream&) const;
template<typename U> friend std::ostream& operator<<(std::ostream& os, darray<U> const& ar);
};
template<typename T>
std::ostream& darray<T>::print(std::ostream& os) const
{
os << "{ ";
for (size_t i = 0; i < m_size; i++)
{
os << m_data[i] << ", ";
if ( i == m_size - 1 )
os << m_data[i];
}
os << " }\n";
return os;
}
template<typename U>
std::ostream& operator<<(std::ostream& os, darray<U> const& obj)
{
return obj.print(os);
}
|
Friend functions in template classes have to be defined inside the class declaration. This is the only way I have found to have the friend function to correctly accept an instance of the templated class with the expected template.
So here I would write:
...
friend std::ostream& operator<<(std::ostream& os, darray<T> const& ar) {
ar.print(os);
return os;
}
...
But beware: your class contains a raw pointer to allocated memory which is probably deleted in the class destructor. Per the rule of five, you must explicitely declare (or delete) the copy/move constructors and assignment operators.
|
74,431,880
| 74,432,050
|
E0349 no operator "<<" matches these operands
|
I try to overload operator << and ++ (post and pre).
This is part of my code, but I get error "e0349: no operator matches these operands".
Could you tell me where I made a mistake?
(C++, VS2022)
#include <iostream>
#include <string>
using namespace std;
class K {
int x, y;
public:
K(int a, int b) :x(a), y(b) {};
K() :x(0), y(0) {};
K operator++(int);
K& operator++();
friend ostream& operator<< (ostream & str, K & obj);
};
K K::operator++(int) {
K temp(*this);
x += 1;
y += 1;
return temp;
}
K& K::operator++() {
x += 1;
y += 1;
return *this;
}
ostream& operator<<(ostream& str, K& obj) {
str << "[" << obj.x << ", " << obj.y << "]";
return str;
}
int main(int argc, char* argv[])
{
K obj{10, 20};
cout << obj++ << endl; //here I get error
cout << obj << endl;
cout << ++obj << endl;
}
|
Simply the post-operator++ is written so that it returns a copy of the temporary value which can be used as rvalue but being that the signature of the insertion operator requires a reference of the value, it does not know how to retrieve the data passed as a copy. This is how you should modify the overloading function of the extract operator:
ostream& operator<<(ostream& str, K const& obj) {
str << "[" << obj.x << ", " << obj.y << "]";
return str;
}
You're simply telling the function that the passed value will have a constant reference that it won't change over time. So it is as if you are taking the reference of the copy value. I know it's very tricky as a thing but I should have cleared your minds enough
|
74,431,937
| 74,431,998
|
Getting a "expected a ')' " error in win32 api c++
|
I have defined ID_BUTTON as 1 and when I try to run the code:
CreateWindow(L"Button", L"TEst", style, monitor.right / 2 - 100, 200, 100, 50, m_hWnd, (HMENU) ID_BUTTON, NULL, NULL);
I get an error saying "expected a ')' "
It works fine if I put NULL instead of "(HMENU) ID_BUTTON", what am I missing?
#include "Window.h"
#define ID_BUTTON 1;
RECT monitor; // deminsions of monitor
Window::Window() : m_hInst(GetModuleHandle(nullptr)) //creates the window
{
WNDCLASS wc = {};
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hInstance = m_hInst;
wc.lpszClassName = ClassName;
wc.lpfnWndProc = WindProc;
RegisterClass(&wc);
DWORD style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
GetWindowRect(GetDesktopWindow(), &monitor);
m_hWnd = CreateWindow(ClassName, WindowTitle, style, 0, 0, 0, 0, NULL, NULL, NULL, NULL);
ShowWindow(m_hWnd, SW_MAXIMIZE);
}
Window::~Window()
{
UnregisterClass(ClassName, m_hInst);
}
LRESULT CALLBACK WindProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) // gets input from user
{
switch (msg) {
case WM_CREATE:
AddControls(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_WINDOWPOSCHANGED:
std::cout << "1";
break;
default:
return DefWindowProcW(hwnd, msg, wp, lp);
}
return 1;
}
bool Window::ProcessMessage()
{
MSG msg = {};
while (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) {
if (msg.message == WM_QUIT)
return false;
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return true;
}
void AddControls(HWND m_hWnd)
{
DWORD style = WS_VISIBLE | WS_CHILD | SS_CENTER;
HWND title = CreateWindow(L"static", L"Welcome", style, monitor.right/2 - 100, 100, 200, 100, m_hWnd, NULL, NULL, NULL);
SendMessage(title, WM_SETFONT, WPARAM(CreateFont(50, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Arial")), true);
CreateWindow(L"Button", L"TEst", style, monitor.right / 2 - 100, 200, 100, 50, m_hWnd, (HMENU) ID_BUTTON, NULL, NULL);
}
|
#define ID_BUTTON 1;
You defined the ID_BUTTON macro as "1;". Macros work as nothing more than a search/replace function. Therefore, after macro expansion, the relevant line now reads:
CreateWindow(L"Button", L"TEst", style, monitor.right / 2 - 100, 200, 100,
50, m_hWnd, (HMENU) 1;, NULL, NULL);
The syntax error should now be obvious. Just drop the semicolon. Macro directives are not C++ statements that must be followed by a semicolon. They live in their own little bubble of the C++ universe.
|
74,432,833
| 74,432,912
|
C++ const std::array size from constructor
|
Say I get an int from a lambda function ran at initialization of a class object. Is it possible to use that int to define the size of a std::array? Something like the following code.
#include <array>
#include <vector>
#include <iostream>
class Test1 {
public:
Test1( std::vector<int> vec1 ) :
nvars([&vec1]() -> int { return vec1.size()+1; }())
{
};
const int nvars;
// ******This isn't allowed!!!!!!!!!
const std::array<int,nvars> arr;
};
int main() {
std::vector<int> vec{1,2,3,4};
Test1 test1(vec);
std::cout << "nvars: " << test1.nvars << std::endl;
return 0;
}
I am a C++ beginner so any other advice will be welcome.
|
No. The size of the array is part of its type. You cannot let it be determined at runtime.
You can have it be determined at compile time, if you do pass a std::array to the constructor. Since C++17 there is CTAD (class template argument deduction) which lets you write:
#include <array>
template <size_t N>
class Test1 {
public:
Test1( std::array<int,N> vec1 ) :
arr(vec1)
{
};
const std::array<int,N> arr;
};
int main() {
std::array vec{1,2,3,4};
Test1 test1(vec);
}
Live Demo
test1 is of type Test1<4>. Note that Test1<4> is a distinct different type than eg Test<5> or Test<24>. If you want one type to have a member array of different size, make it a std::vector.
|
74,432,989
| 74,433,078
|
Overloading the arithmetic operators using friend functions
|
I found an example of how to overload arithmetic operators using friend functions, and the overloaded operator function is defined inside the class with comments stating that:
/* This function is not considered a member of the class, even though the definition is
inside the class */
this is the example:
#include <iostream>
class Cents
{
private:
int m_cents {};
public:
Cents(int cents) : m_cents{ cents } { }
// add Cents + Cents using a friend function
// This function is not considered a member of the class, even though the definition is inside the class
friend Cents operator+(const Cents& c1, const Cents& c2)
{
// use the Cents constructor and operator+(int, int)
// we can access m_cents directly because this is a friend function
return Cents{c1.m_cents + c2.m_cents};
}
int getCents() const { return m_cents; }
};
int main()
{
Cents cents1{ 6 };
Cents cents2{ 8 };
Cents centsSum{ cents1 + cents2 };
std::cout << "I have " << centsSum.getCents() << " cents.\n";
return 0;
}
Is this function really not a member of that class? and are all friend functions defined inside the class but not a member of that class or
It is only for overloaded functions using the friend keyword.
|
From the C++ 17 Standard (12.2 Class members)
2 A member-declaration does not declare new members of the class if it
is
(2.1) — a friend declaration (14.3),
(2.2) — a static_assert-declaration,
(2.3) — a using-declaration (10.3.3), or
(2.4) — an empty-declaration.
For any other member-declaration, each declared entity that is not an
unnamed bit-field (12.2.4) is a member of the class, and each such
member-declaration shall either declare at least one member name of
the class or declare at least one unnamed bit-field.
and (14.3 Friends)
1 A friend of a class is a function or class that is given permission
to use the private and protected member names from the class. A class
specifies its friends, if any, by way of friend declarations. Such
declarations give special access rights to the friends, but they do
not make the nominated friends members of the befriending class.
So friend functions are not members of the class where they are declared as friend functions even if they are also defined in the class.
|
74,434,270
| 74,434,522
|
Ceres solver - Set size of parameter block of CostFunction
|
in this Ceres example, SizedCostFunction<1,1> is used. I would like to change it to CostFunction since I do not know the size of input parameters during compilation time. I found out that the number of residuals can be easily changed with set_num_residuals(int), however, I cannot find a way to set the number of inputs. Could you tell me how to set it?
class QuadraticCostFunction
: public SizedCostFunction<1 /* number of residuals */,
1 /* size of first parameter */> {
public:
bool Evaluate(double const* const* parameters,
double* residuals,
double** jacobians) const override {
double x = parameters[0][0];
// f(x) = 10 - x.
residuals[0] = 10 - x;
if (jacobians != nullptr && jacobians[0] != nullptr) {
jacobians[0][0] = -1;
}
return true;
}
};
|
You can call from QuadraticCostFunction these protected CostFunction member fuctions:
set_num_residuals(num);
*mutable_parameter_block_sizes() = std::vector<int32_t>{ /* size_1, ..., size_num */ };
You don't seem to need to inherit SizedCostFunction.
class QuadraticCostFunction
: public CostFunction {
|
74,434,337
| 74,475,762
|
how to add a dependecy to a system library in my conanfile .py?
|
My ConanFile.py for TWSAPI's C++ code
from conans import ConanFile, CMake, tools
IBKR_VERSION = "10.18.01"
class TwsApiConan(ConanFile):
name = "twsapi"
version = IBKR_VERSION
license = "NA"
url = "URL_TO_CODE_FORK"
description = "Built from a mirror of the actual TWS API files in Github"
topics = ("tws", "interactive brokers")
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False]}
default_options = {"shared": False}
generators = "cmake"
def source(self):
self.run("git clone --depth 1 --branch " + IBKR_VERSION + " git@github.com/tws-api.git")
tools.replace_in_file("tws-api/CMakeLists.txt", " LANGUAGES CXX )",
''' LANGUAGES CXX )
add_compile_options(-std=c++17)''')
def build(self):
cmake = CMake(self)
cmake.configure(source_folder="tws-api")
cmake.build()
def package(self):
self.copy("*.h", dst="include", src="tws-api/source/cppclient/client")
self.copy("*.lib", dst="lib", keep_path=False)
self.copy("*.dll", dst="bin", keep_path=False)
self.copy("*.so", dst="lib", keep_path=False)
self.copy("*.dylib", dst="lib", keep_path=False)
self.copy("*.a", dst="lib", keep_path=False)
def package_info(self):
self.cpp_info.libs = ["twsapi"]
Recently TWSAPI added a requirement for an obscure library.. which I have installed locally and linked in an downstream project.. but does it make sense to move that dependency into this ? I tried the following but don't see any change or signal that the libs were picked up.. is it merely my job to find them and add them under self.copy as well?
Conan References : https://github.com/conan-io/conan/issues/8044#issuecomment-726053437
Debian Package containing the libs : https://packages.debian.org/sid/libintelrdfpmath-dev
def package_info(self):
self.cpp_info.libs = ["twsapi", "bidgcc000"] <--- merely calling it out doesn't work
|
I think you're looking for self.cpp_info.system_libs:
def package_info(self):
self.cpp_info.libs = ["twsapi"]
self.cpp_info.system_libs = ["bidgcc000"]
|
74,435,017
| 74,440,081
|
Getting " Cannot open source file "pugixml.hpp" " error
|
When I try to build solution in visual studio I get an error saying :
Cannot open source file "pugixml.hpp" along with some other errors , such as :
Cannot open include file: 'cereal/types/list.hpp': No such file or directory.
I downloaded the code onto my local machine from a SVN repository and the solution is an integration of C++ and C#. Could it be due to my limited access to the repo or not.
Thanks
I looked it up on the internet and I tried going to the project properties and adding the directory manually but I didn't work. I am not professional , so maybe I haven't done this properly.
|
Generally speaking, downloading an external library needs to include its library directory and various header file directories.
If a dll is used, this document explains how to use the dll.
Regarding Cannot open source file "...hpp", you could refer to the method in this issue.
|
74,435,189
| 74,463,042
|
How to create a synthetic keyboard event in wxWidgets to trigger shortcuts set in a wxAcceleratorEntry?
|
I am using wxWebView in my application. Since this widget consumes all keyboard events internally, I have to create a synthetic keyboard event and process it. This is the code that I am using for creating a synthetic keyboard event:
// create a synthetic keyboard event and handle it
wxKeyEvent keyEvent( wxEVT_KEY_DOWN );
keyEvent.SetEventObject( ctrl_ );
auto key = url.substr( keyCodePrefix_.length() );
if( key == "Escape" )
keyEvent.m_keyCode = WXK_ESCAPE;
else if( key == "F1" )
keyEvent.m_keyCode = WXK_F1;
else
keyEvent.m_keyCode = WXK_NONE;
ctrl_->ProcessWindowEvent( keyEvent );
As you could see, I only handle Escape and F1 keys for now. The type of keyboard event that I am using is wxEVT_KEY_DOWN. Everything works fine. According to the doc, the keyboard is processed in the widget then is sent to the application. However it does not trigger the shortcuts are set in the parent window ( that contains wxWebView widget ) via wxAcceleratorTable.
How should I create a keyboard event that trigger shortcuts in my accelerator table?
I tried to set the type of keyboard event to wxEVT_CHAR but it also did not work.
Update: my event handler is like below:
class MyApp : public wxApp
{
public:
MyApp();
bool OnInit() override;
// ...
bool ProcessEvent(wxEvent& event) override
{
if( event.GetEventType() == wxEVT_KEY_DOWN )
{
wxKeyEvent& ke = (wxKeyEvent&)event;
if( ke.GetKeyCode() == WXK_ESCAPE )
{
// handle keyboard event
}
event.Skip(); // this does not help!
}
return wxApp::ProcessEvent( event );
}
// ...
DECLARE_EVENT_TABLE()
};
|
I used sendInput function of Win32 to create a synthetic key down event. It is exactly emulating keyboard events which means it triggers the shortcuts in accelerator table. Also be noticed that the keyboard event goes to the focused widget.
INPUT inputs[ 2 ] = {};
ZeroMemory( inputs, sizeof( inputs ) );
auto key = url.substr( keyCodePrefix_.length() );
if( key == "Escape" )
{
// key down
inputs[ 0 ].type = INPUT_KEYBOARD;
inputs[ 0 ].ki.wVk = VK_ESCAPE;
// key up
/*inputs[ 1 ].type = INPUT_KEYBOARD;
inputs[ 1 ].ki.wVk = VK_ESCAPE;
inputs[ 1 ].ki.dwFlags = KEYEVENTF_KEYUP;*/
}
else if( key == "F1" )
{
// key down
inputs[ 0 ].type = INPUT_KEYBOARD;
inputs[ 0 ].ki.wVk = VK_F1;
// key up
/*inputs[ 1 ].type = INPUT_KEYBOARD;
inputs[ 1 ].ki.wVk = VK_F1;
inputs[ 1 ].ki.dwFlags = KEYEVENTF_KEYUP;*/
}
SendInput( ARRAYSIZE( inputs ), inputs, sizeof( INPUT ) );
|
74,435,920
| 74,479,298
|
Acyclic undirected graph allocation problem
|
We have an allocation problem: each node is a fuel source, and every edge contains a number of evenly spaced out lamps (think of them as being 1 m apart from each other). Each fuel source can power lamps that are on the immediate edges around it (it cannot fuel lamps through other nodes). A fuel source also has a radius in which it fuels lamps around it - depending on the radius (in meters) we can calculate the amount of fuel a give fuel source provides - example: a fuel source with a radius of 2 can fuel all the lamps within its radius and, in total, uses up 2 liters of fuel (fuel usage is a function of the radius).
Note that two nodes have only one path between each other (meaning that that the number of edges is equal to the number of nodes - 1).
The goal is to calculate the optimal radii of the fuel sources so that we minimize the fuel usage while fueling all the lamps.
Here is an example graph
The solution to this graph looks like this. The red ellipsoids are supposed to visualize the radii of the fuel sources, and below is a table of the relevant values:
Node, fuel source
Radius, fuel consumption
0
1
1
2
2
0
3
2
4
0
5
0
After we add up all the fuel amounts, we get the result: 5.
The input for the above task looks like this:
6 // 6 nodes (numVertices)
0 1 3 // Node 0 with an edge containing 3 nodes going to node 3 (src dest lights)
1 2 1 // ...
2 3 2
1 4 2
1 5 2
So far I've tried loading up my edges like this (note that this solution is quite cursed, especially with my use of pointers):
struct light {
int count;
};
struct node {
int d;
light* l;
};
std::vector<node*>* tree;
int numVertices;
// Do this for all values in the input
void AddEdge(int src, int dest, int lights) {
light* l = new light{ lights };
tree[src].push_back(new node{ dest, l });
tree[dest].push_back(new node{ src, l });
}
And then I solved the graph by using a greedy algorithm to 'remove' as many lamps per step as possible:
void Solve() {
int fuel = 0;
while (true) {
int maxNode = 0;
int maxNodeLights = 0;
for (int A = 0; A < numVertices; A++)
{
int lightsOnNode = 0;
for (node* B : tree[A])
{
lightsOnNode += B->l->count;
}
if (lightsOnNode > maxNodeLights) {
maxNodeLights = lightsOnNode;
maxNode = A;
}
}
if (maxNodeLights > 0) {
bool addedRange = false;
for (node* B : tree[maxNode])
{
if (B->l->count > 0) {
B->l->count--;
addedRange = true;
}
}
if (addedRange) {
fuel++;
}
}
else {
break;
}
}
std::cout << fuel << '\n';
}
If we were to parse the input string from the example case it would look like this:
numVertices = 6;
AddEdge(0, 1, 3);
AddEdge(1, 2, 1);
AddEdge(2, 3, 2);
AddEdge(1, 4, 2);
AddEdge(1, 5, 2);
Solve();
This works for simple graphs like the one above, but it fails by a small margin once a more complex graph is introduced, since the greedy algorithm doesn't look ahead if there is a better option a couple steps in the future.
A long test case can be found here. The fuel amount consumed by this graph is 77481.
New, failing test cases:
1 0 4
2 1 1
3 2 4
4 3 1
5 1 2
6 1 1
7 2 2
8 3 2
9 1 1
10 1 3
11 5 1
12 0 2
13 10 4
14 3 3
15 5 4
(Output: 16. Correct output: 17)
1 0 2
2 1 3
3 2 2
4 1 4
5 4 3
6 3 2
7 5 3
8 3 4
(Output: 10. Correct output: 11)
1 0 4
2 0 3
3 0 4
4 3 3
5 2 2
6 3 1
7 2 1
8 3 2
9 3 2
10 2 1
11 9 1
12 4 2
13 5 2
14 8 2
15 9 1
16 14 2
17 3 3
18 3 4
(Output: 15. Correct output: 16)
|
Algorithm pseudocode:
WHILE lamps remain unfueled
LOOP over sources
IF source has exactly one edge with unfueled lamps
SET fuel source to source at other end of unfueled edge
INCREMENT radius of fuel source with unfueled edge lamp count
LOOP over edges on fuel source
IF edge fueled lamp count from fuel sourve < fuel source radius
SET edge fueled lamp count from fuel source to fuel source radius
C++ code for this is at https://github.com/JamesBremner/LampLighter.
Sample output
Input
0 1 1
1 2 1
2 3 1
3 4 1
0 5 1
5 6 1
6 7 1
7 8 1
0 9 1
9 10 1
10 11 1
11 12 1
Source radii
0 r=0
1 r=1
2 r=0
3 r=1
4 r=0
5 r=1
6 r=0
7 r=1
8 r=0
9 r=1
10 r=0
11 r=1
12 r=0
Total fuel 6
Handling different numbers of lamps on each edge
0 1 3
1 2 1
0 5 3
5 6 1
Source radius
0 r=2
1 r=1
2 r=0
5 r=1
6 r=0
Total fuel 4
Another test
lamp ..\test\data11_19_2.txt
Output:
1 0 2
2 1 3
3 2 2
4 1 4
5 4 3
6 3 2
7 5 3
8 3 4
Source radius
1 r=3
0 r=0
2 r=0
3 r=4
4 r=0
5 r=3
6 r=0
7 r=0
8 r=0
Total fuel 10
Acknowledgement: This algorithm is based on an insight from MarkB who suggested that fueling should begin at leaf nodes and work "downwards"
|
74,436,273
| 74,438,729
|
AVX2 _mm256_cmp_pd to return number values
|
My goal is to vectorize comparisons to use them as a masks in the future.
The problem is that _mm256_cmp_pd returns NaN instead of 1.0. What is the correct way to do comparisons in AVX2?
AVX2 code:
__m256d _numberToCompare = _mm256_set1_pd(1.0);
__m256d _compareConditions = _mm256_set_pd(0.0, 1.0, 2.0, 3.0);
__m256d _result = _mm256_cmp_pd(_numberToCompare, _compareConditions, _CMP_LT_OQ); //a < b ordered (non-signalling)
alignas(8) double res[4];
_mm256_store_pd(&res[0], _result);
for (auto i : res) {
std::cout << i << '\t';
}
__m256d _result2 = _mm256_cmp_pd(_numberToCompare, _compareConditions, _CMP_LE_OQ); //a <= b ordered (non-signalling)
alignas(8) double res2[4];
_mm256_store_pd(&res2[0], _result2);
for (auto i : res2) {
std::cout << i << '\t';
}
std::cout << '\n';
GodBolt link
Expected result (one I would have in scalar code):
0 0 1 1
0 1 1 1
Actual result:
-nan -nan 0 0
-nan -nan -nan 0
Why result of comparison is NaN?
What is the correct way to get expected result?
|
Ad 1: The result is a bitmask (in binary 0xffff'ffff'ffff'ffff for true or 0 for false) which can be used with bitwise operators.
Ad 2: You can compute _result = _mm256_and_pd(_result, _mm256_set1_pd(1.0)) if you really want 1 and 0 (but usually, using the bitmask directly is more efficient).
Also be aware that _mm256_set_pd takes the arguments in "big-endian" order, i.e., the element with the highest address is the first argument (don't ask me why Intel decided that way) -- you can use _mm256_setr_pd instead if you prefer little-endian.
|
74,436,602
| 74,436,751
|
Using std string accessor with ostream operator <<
|
If I create a class:
// First Example
#include <iostream>
#include <string>
class my_class {
std::string str;
public:
my_class(const char* s = "") : str(s) {}
operator const char* () const { return str.data(); } // accessor
};
my_class mc1{"abc"};
std::cout << mc1; // Calls the char* accessor and successfully writes "abc" to screen output.
If I modify the class thus:
// Second Example
class my_class {
std::string str;
public:
my_class(const char* s = "") : str(s) {}
operator std::string () const { return str; } // accessor
};
my_class mc1{"abc"};
std::string mystring = mc1; // Calls the string accessor
std::cout << mystring; // Also successfully writes "abc" to screen output.
However, if I try to call:
std::cout << mc1;
I will get a page full of compilation errors that begin with:
error C2679: binary '<<': no operator found which takes a right-hand operand of type 'my_class' (or there is no acceptable conversion)
I can correct this error by adding to the second example class:
friend std::ostream& operator <<(std::ostream& os, my_class& rhs) {
os << rhs.str;
return os;
}
which I mostly cribbed from one of the suggested solutions to this problem. But I don't understand why it is necessary using a string accessor but not a char* accessor.
I was expecting successful compilation and output of the value of mc1.str, OR I would have expected the same error trying to use the char* accessor function in the fist example. Instead I received C2679 on the second example only.
UPDATE: I see that using a cast operator in the ostream, e.g. std::cout << (std::string)mc1;, will explicitly invoke the string accessor and write the string to the screen.
|
This happens because of how the functions are defined.
For the const char* case, the operator << that cout has available for that is declared as:
template< class CharT, class Traits >
basic_ostream<CharT, Traits>&
operator<<( basic_ostream<CharT, Traits>& os, const char* s );
So, when the compiler analyzes std::cout << mc1;, it can deduce what CharT and Traits are from cout, and it finds my_class::operator const char* () to convert mc1 into a const char*, so overload resolution is successful and the code compiles.
When you switch to having operator std::string () and use std::cout << mc1;, you now need to call the std::string overload for operator <<, which is declared as:
template< class CharT, class Traits, class Allocator >
std::basic_ostream<CharT, Traits>&
operator<<( std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str );
In this overload, not only does the first parameter rely on the template parameters, but so does the second parameter. This means the compiler is going to try and deduce the types of CharT, Traits and Allocator from mc1 directly. No conversion operators are considered during this step, and since mc1 is not actually a std::string, deduction fails and you are left with no possible overloads, so the code fails to compile.
|
74,436,806
| 74,438,164
|
What precisely is an expression?
|
Consider whether x in the declaration int x; is an expression.
I used to think that it's certainly not, but the grammar calls the variable name an id-expression here.
One could then argue that only expression is an expression, not ??-expression. But then in 1 + 2, neither 1 nor 2 match, because those are additive-expression and multiplicative-expression respectively, not expressions. But common sense says those should be called expressions too.
We could decide that any ??-expression (including expression) is an expression, but then the variable name in a declaration matches as well.
We could define an expression to be any ??-expression except id-expression, but this feels rather arbitrary.
What's the right grammatical definition of an expression, and is the variable name in its declaration an expression or not?
|
After looking at the links provided by @LanguageLawyer (1, 2), I'm convinced the consensus is that id-expression is a misnomer, and not always an expression (e.g. it's not an expression in a declaration).
Then, a source substring is an expression if at least one of its parents in the parse tree is called:
expression, or
*-expression1 but not id-expression
, and that parent expands exactly to this substring and nothing more.
This is the same definition @n.m. proposed, except I allow "*-expression and not id-expression" nodes as well.
1 * is a wildcard for any string.
|
74,436,888
| 74,436,961
|
Uniqueness of objects in shared pointers
|
Let's consider code below:
class A {
string a;
public A(string a) : a(a) { }
};
class B : public A {
public B(string a) : A(a) { }
};
int main() {
std::shared_ptr<A> x1 = std::make_shared<B>("x");
std::shared_ptr<A> x2 = std::make_shared<B>("x");
A* atom1 = x1.get();
A* atom2 = x2.get();
A* atom1X = std::make_shared<B>("x").get();
A* atom2X = std::make_shared<B>("x").get();
bool condition1 = (atom1 == atom2);
bool condition2 = (atom1X == atom2X);
}
The result is surprising me because condition1 is false but condition2 is true.
Why? Can you explain what is going on here?
I was researching on the internet. I want to understand how it works
|
A* atom1X = std::make_shared<B>("x").get(); // (1)
A* atom2X = std::make_shared<B>("x").get(); // (2)
In these definitions, std::make_share<B>("x") creates a temporary std::shared_ptr that ceases to exist at the end of the full expression (essentially at the next ;). That means that the object each of these pointers points to gets destroyed immediately after being created.
By the time atom2X is declared the object pointed to by atom1X has been destroyed and its storage deallocated. It just so happens that the storage previously occupied by the object allocated in line (1) is exactly the right size to hold a B object, so it gets re-used in line (2).
Essentially, if you remove all of the smart pointers, you can think of your code as being equivalent to this:
A* x1 = new B("x");
A* x2 = new B("x");
A* atom1 = x1;
A* atom2 = x2;
A* atom1X = new B("x");
delete atom1X;
A* atom2X = new B("x");
delete atom2X;
|
74,437,204
| 74,437,260
|
Is this indirect const access an UB?
|
When I was checking some code today, I noticed an old method for implementing std::enable_shared_from_this by keeping a std::weak_ptr to self in the constructor. Somthing like this:
struct X {
static auto create() {
auto ret = std::shared_ptr<X>(new X);
ret->m_weak = ret;
return ret;
}
// use m_weak.lock() to access the object
//...
private:
X() {}
std::weak_ptr<X> m_weak;
};
But then something came to me regarding constness of this object. Check the following code:
struct X {
static auto create() {
auto ret = std::shared_ptr<X>(new X);
ret->m_weak = ret;
return ret;
}
void indirectUpdate() const {
m_weak.lock()->val = 1;
}
void print() const {
std::cout << val << '\n';
}
private:
X() {}
std::weak_ptr<X> m_weak;
int val = 0;
};
int main() {
auto x = X::create();
x->print();
x->indirectUpdate();
x->print();
}
In this code, indirectUpdate() is a const method and it should not update our object, but in fact it does. Because std::weak_ptr.lock() returns a non-const shared_ptr<> even though the method is const. So you will be able to update your object indirectly in a const method. This will not happen in case of std::enable_shared_from_this because shared_from_this returns a shared pointer to const ref of object in const method. I wonder if this code is UB or not. I feel it should be, but I'm not sure. Any idea?
Update:
Sorry, it seems that my question was not relayed correctly. I meant even if we have a const pointer, we lose that constness via this method. following code shows that:
struct X {
static auto create() {
auto ret = std::shared_ptr<X>(new X);
ret->m_weak = ret;
return ret;
}
void show() const { std::cout << "const \n";}
void show() { std::cout << "non-const\n";}
void indirectUpdate() const {
show();
m_weak.lock()->show();
m_weak.lock()->val = 1;
}
void print() const {
std::cout << val << '\n';
}
int val = 0;
private:
X() {}
std::weak_ptr<X> m_weak;
};
int main() {
// Here we have a const pointer
std::shared_ptr<const X> x = X::create();
x->print();
x->indirectUpdate();
x->print();
}
and output will be following:
0
const
non-const
1
which shows losing constness.
|
The object that is modified is not const. There is no undefined behavior.
Add a method like this:
#include <memory>
#include <iostream>
struct X {
static auto create() {
auto ret = std::shared_ptr<X>(new X);
ret->m_weak = ret;
return ret;
}
void show() const { std::cout << "const \n";}
void show() { std::cout << "non-const\n";}
void indirectUpdate() const {
m_weak.lock()->show();
m_weak.lock()->val = 1;
}
void print() const {
std::cout << val << '\n';
}
private:
X() {}
std::weak_ptr<X> m_weak;
int val = 0;
};
int main() {
auto x = X::create();
x->print();
x->indirectUpdate();
x->print();
}
To get this output:
0
non-const
1
Modifying an object via a const mehtod is ok, as long as the method only modifies an object that is actually not const.
It is similar to using a const & to a non-const object. You may cast away constness and modify it as long as the object is really not const:
#include <iostream>
int main() {
int x = 0;
const int& ref = x;
const_cast<int&>(ref) = 42;
std::cout << x;
}
I also see no danger of misusing the pattern in your code, because once the object is const you won't be able to assign to its val member and all is fine with constcorrectness.
In your Update you have a const pointer in main but the object is still not const. Consider this simpler example:
#include <iostream>
struct foo {
static foo* create(){
auto x = new foo();
x->self = x;
return x;
}
void bar() const {
this->self->non_const();
}
void non_const() {
std::cout << "Hello World\n";
}
foo* self;
};
int main() {
const foo* f = foo::create();
f->bar();
delete f;
}
Its not quite the same as yours, but it has similar effect of calling a non-const method on a seemingly const object. Though its all fine.
The only foo object is that created in foo::create, it is not constant. In main we have a const foo* to that object. main can only call the const member bar. Inside bar the this pointer is a const foo*, but self does not point to a const foo. self itself is `const, but not the object it points to.
|
74,437,249
| 74,437,761
|
Can I create a second vector which contains the identical objects as the first vector?
|
I am trying to convert a performance critical part of a Java code to a C++ code.
In Java I work with lists containing a small sample of the original list. When I add objects of the first list to the second list actually only a reference to the object is stored, so I do not copy the object. This is what I would like to achieve in C++ also. Unfortunately I have not found a way to do so as the push_back method seems to create a deep copy instead.
Java code:
class Data {
Data(int id){
this.id = id;
this.name = "Name " + id;
}
public int id;
public String name = "";
public boolean isFancy = false;
}
public class Main {
public static void main(String[] args) {
List<Data> dataList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Data data = new Data(i);
dataList.add(data);
}
List<Data> dataSublist = new ArrayList<>();
dataSublist.add(dataList.get(2));
dataSublist.add(dataList.get(3));
dataSublist.add(dataList.get(8));
dataSublist.forEach(data -> data.isFancy = true); // change isFancy in subList to alter the original object
System.out.println("Data 3 original isFancy = " + dataList.get(3).isFancy); // is true
}
}
C++ code:
class Data {
public:
Data(int id) { id_ = id; };
int id_ = 0;
std::string name_ = "";
bool isFancy_ = false;
};
int main()
{
std::vector<Data> dataList;
for (int i = 0; i < 10; i++) {
Data data = Data(i);
dataList.push_back(data);
}
std::vector<Data> dataSublist;
dataSublist.push_back(dataList[2]);
dataSublist.push_back(dataList[3]);
dataSublist.push_back(dataList[8]);
for (int i = 0; i < dataSublist.size(); i++) {
dataSublist[i].isFancy_ = true; // change isFancy in subList to alter the original object
}
std::cout << "Data 3 original isFancy = " << ((dataList[3].isFancy_) ? "true" : "false"); // is false
}
How to I get the output to "true" here?
|
The learning curve for C++ is not the best. I don't think it's a good idea to just jump into it and try to write efficient code without any experience. Anyway, here it is, I hope it helps:
#include <string>
#include <vector>
#include <memory>
#include <iostream>
class Data
{
public:
Data(int id)
: id_{id}
{
}
int id_;
std::string name_ = "";
bool isFancy_ = false;
};
int main()
{
std::vector<std::shared_ptr<Data>> dataList{};
for (int i = 0; i < 10; i++)
{
std::shared_ptr<Data> data = std::make_shared<Data>(i); // Equivalent to `new Data(i)` in Java.
dataList.push_back(data);
}
std::vector<std::shared_ptr<Data>> dataSublist{};
dataSublist.push_back(dataList[2]);
dataSublist.push_back(dataList[3]);
dataSublist.push_back(dataList[8]);
for (auto data : dataSublist)
{
// The `->` represents an indirection and has nothig to do with lambdas.
data->isFancy_ = true;
}
std::cout << "Data 3 original isFancy = " << std::boolalpha << dataList[3]->isFancy_ << std::endl;
}
|
74,437,901
| 74,438,830
|
g++ std=c++11 : is anything wrong in allocating/deallocating a 2d array this way
|
I'm using g++ -std=c++11 and this compact approach to allocate/deallocate 2d arrays :
int(*MyArray)[Ydim]=new int[Xdim][Ydim];
delete[] MyArray;
Everything seems to be working fine (compile time and run time).
I know there are many ways to do the same but this is compact and seems to be doing the job.
Is anything wrong with it?
Everything seems to work...but worried about subtle problems (memory leakage...)
Xdim and Ydim are compile time constants
|
Assuming you want to stick to your current instantiation, I don't think you will receive any memory leak problems. If your internal nested array was a pointer as well you would need to de-allocate before de-allocating the external one.
Alternatives to avoid Dynamic Allocation:
To avoid the "new" and "delete" operators, and ease your worries about "subtle problems"
I would highly advise a swap to
std::vector<std::vector<int>> myArray(Xdim,std::vector<int>(Ydim,0));
I may even suggest you move to a flattened vector
std::vector<int> myArray = {Xdim * Ydim};
Better yet because your sizes are known at compile time in this case using std::array is preferential to vector.
std::array<std::array<int,Ydim>,Xdim> myArray = {};
or if you have the ability to use 3rd party libraries and specifically you are working with images I've found great success with OpenCV Matrices to represent 2 dimensional arrays.
|
74,438,015
| 74,439,229
|
Error while using EVP_MD_CTX_cleanup(ctx ) in C++ using openssl 1.1.0
|
I am trying to run/compile old code that was made in 2018 using an old OpenSSL version.
I faced so many errors, but I solved them all. Now I'm just stucking with last error on this line:
EVP_MD_CTX_cleanup(ctx)
The error is here:
error: ‘EVP_MD_CTX_cleanup’ was not declared in this scope; did you mean ‘EVP_MD_CTX_create’?
22 | if ( EVP_MD_CTX_cleanup(ctx ) != 1 ) { }
The code for that part is below:
#ifndef SHA256_HPP
#define SHA256_HPP
#include <openssl/evp.h>
#include <array>
class sha256
{
public:
inline sha256()
: ctx()
{
if ( EVP_DigestInit_ex(ctx, EVP_sha256(), nullptr ) != 1 ) {
throw "EVP_DigestInit_ex() failed";
}
}
inline ~sha256()
{
if ( EVP_MD_CTX_cleanup(ctx ) != 1 ) { }
}
sha256( sha256 const& ) = delete;
sha256& operator=( sha256 const& ) = delete;
sha256( sha256&& ) = delete;
sha256& operator=( sha256&& ) = delete;
inline std::array<unsigned char, 32> hash( unsigned char const* const data, int const len )
{
if ( EVP_DigestUpdate(ctx, data, len ) != 1 ) {
throw "EVP_DigestUpdate() failed";
}
std::array<unsigned char, 32> hash;
unsigned int hash_size = sizeof( hash );
if ( EVP_DigestFinal_ex(ctx, hash.data(), &hash_size ) != 1 ) {
throw "EVP_DigestFinal_ex() failed";
}
if ( hash_size != sizeof( hash ) ) {
throw "unexpected hash size";
}
return hash;
}
private:
EVP_MD_CTX *ctx;
};
#endif // SHA256_HPP
I tried:
if ( EVP_MD_CTX_free(ctx ) != 1 )
if ( EVP_MD_CTX_destroy (ctx ) != 1 )
But still, I have the same error.
Any ideas what I have to change to make it run on Openssl 1.1.0 on cygwin64?
|
OpenSSL 1.1.0 is not that old, just a few years. Are you sure that is the correct version you are supposed to be using? More likely, you should be using 1.0.2 instead, as EVP_MD_CTX_cleanup() doesn't exist in 1.1.0.
One of the major changes in 1.1.0 was changing the majority of OpenSSL's structs into opaque pointers instead. The code you showed should not work in any version, as you are passing a null EVP_MD_CTX* pointer to all of the EVP_Digest...() functions, which will not work.
The code likely looked more like this originally, before you mucked around with it:
class sha256
{
public:
inline sha256()
{
EVP_MD_CTX_init(&ctx); // <-- init with this
if ( EVP_DigestInit_ex(&ctx, ...) != 1 ) { // <-- use '&' here
...
}
}
inline ~sha256()
{
if ( EVP_MD_CTX_cleanup(&ctx) != 1 ) { } // <-- use '&' here
}
...
inline std::array<unsigned char, 32> hash( unsigned char const* const data, int const len )
{
if ( EVP_DigestUpdate(&ctx, ...) != 1 ) { // <-- use '&' here
...
}
...
if ( EVP_DigestFinal_ex(&ctx, ...) != 1 ) { // <-- use '&' here
...
}
...
}
private:
EVP_MD_CTX ctx; // <-- no '*' here
};
In OpenSSL 1.1.0, that would look like this instead:
class sha256
{
public:
inline sha256()
{
ctx = EVP_MD_CTX_new(); // <-- init with this
if ( !ctx ) {
...
}
if ( EVP_DigestInit_ex(ctx, ...) != 1 ) { // <-- no '&' here
...
}
}
inline ~sha256()
{
EVP_MD_CTX_free(ctx); // <-- no '&' here
}
...
inline std::array<unsigned char, 32> hash( unsigned char const* const data, int const len )
{
if ( EVP_DigestUpdate(ctx, ...) != 1 ) { // <-- no '&' here
...
}
...
if ( EVP_DigestFinal_ex(ctx, ...) != 1 ) { // <-- no '&' here
...
}
...
}
private:
EVP_MD_CTX *ctx; // <-- use '*' here
};
|
74,439,230
| 74,443,325
|
C++ how to make it so a double variable can only have numbers entered in using cin
|
void addNumbers(vector<double> &vec) {
double add_num {};
cout << "Enter an integer to add: ";
cin >> add_num;
vec.push_back(add_num);
cout << add_num << " added" << endl;
}
The vector is empty, and I only want people to be able to add numbers into it, and whenever they try anything else it says "Invalid number".
The full code is below, and currently it just loops over and over saying "0.00 added" if I put something other than a number in lol
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <iomanip>
#include <cctype>
using namespace std;
char choice {};
char menu();
void print(vector<double>);
void mean(vector<double>);
void addNumbers(vector<double> &vec);
void smallest(vector<double>);
void largest(vector<double>);
char menu() {
cout << "\nP - Print numbers" << endl;
cout << "A - Add a number" << endl;
cout << "M - Display mean of the numbers" << endl;
cout << "S - Display the smallest number" << endl;
cout << "L - Display the largest number" << endl;
cout << "Q - Quit" << endl;
cout << "\nEnter your choice: ";
cin >> choice;
choice = toupper(choice);
return choice;
}
void print(vector<double> vec) {
if (vec.size() != 0) {
cout << "[ ";
for (auto i : vec) {
cout << i << " ";
}
cout << "]";
}
else {
cout << "[] - the list is empty" << endl;
}
}
void addNumbers(vector<double> &vec) {
double add_num {};
cout << "Enter an integer to add: ";
cin >> add_num;
vec.push_back(add_num);
cout << add_num << " added" << endl;
}
void mean(vector<double> vec) {
if (vec.size() != 0) {
double result {};
for (auto i : vec) {
result += i;
}
cout << "The mean is " << result / vec.size() << endl;
}
else {
cout << "Unable to calculate the mean - no data" << endl;
}
}
void smallest(vector<double> vec) {
if (vec.size() != 0) {
cout << "The smallest number is " << *min_element(vec.begin(), vec.end()) << endl;
}
else {
cout << "Unable to determine the smallest number - list is empty" << endl;
}
}
void largest(vector<double> vec) {
if (vec.size() != 0) {
cout << "The largest number is " << *max_element(vec.begin(), vec.end()) << endl;
}
else {
cout << "Unable to determine the largest number - list is empty" << endl;
}
}
int main() {
vector<double> vec {};
bool done {true};
cout << fixed << setprecision(2);
do {
menu();
switch (choice) {
case 'P':
print(vec);
break;
case 'A': {
addNumbers(vec);
break;
}
case 'M': {
mean(vec);
break;
}
case 'S': {
smallest(vec);
break;
}
case 'L':
largest(vec);
break;
case 'Q':
cout << "Goodbye" << endl;
done = false;
break;
default:
cout << "Unknown selection, please try again" << endl;
}
} while (done == true);
return 0;
}
|
You need to check the return code of your extraction command cin >> add_num. And in general, you need to check the state of a stream after any IO operation.
So, what could happen? If you enter any invalid data, like for example "abc", then cin >> add_num will of course not work, and the state of the stream (cin) will set one of its failure bits. Please urgently check this.
And the failure will stay, unless you clear it. All further activities on cin will fail. SO, you need to call the clear() function of the stream. But this alone will not help. There may still be invalid characters in the input stream. And those must be eliminated.
You may use the ignore function for that:
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
And if you want to make sure to get the needed values, then you could come up with something like the below:
#include <iostream>
#include <vector>
#include <limits>
using namespace std;
void addNumbers(vector<double> &vec) {
double add_num {};
bool isValidNumber{};
while (not isValidNumber) {
cout << "Enter an integer to add: ";
if (cin >> add_num) {
isValidNumber = true;
}
else {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
}
vec.push_back(add_num);
cout << add_num << " added" << endl;
}
int main() {
std::vector<double> values{};
addNumbers(values);
}
|
74,439,722
| 74,439,730
|
What would be the long form of the following statment?
|
I was looking at some code which came with the following short-hand statement
score = ((initialPlayer == player) ? CAPTURE_SCORE : -CAPTURE_SCORE) + recursive_solver(lastMap, initialPlayer, findOpponent(player), 1 + rounds);
I think that I understand the first portion of the code,
if(initialPlayer == player){
score = CAPTURE_SCORE;
}
else
score = -CAPTURE_SCORE;
but im confused to how the +recursive_solver function is added to this, any help would be greatly appreciated :)
As stated above I tried to write out the statement in a longer from thats easier for me to read. My best guess is that the recursive solver function is then added to the score of the if-else statement?
|
if(initialPlayer == player)
score = CAPTURE_SCORE + recursive_solver(lastMap, initialPlayer, findOpponent(player), 1 + rounds);
else
score = -CAPTURE_SCORE + recursive_solver(lastMap, initialPlayer, findOpponent(player), 1 + rounds);
Explanation:
A = (C ? B : D) + E;
If C is true: A = (B) + E;
If C is false: A = (D) + E;
In sum
if (C)
A = B + E;
else // if (!C)
A = D + E;
|
74,439,812
| 74,439,919
|
Unary Predicate results in error "called object type 'bool' is not a function or function pointer" in remove_if
|
I'm trying to use remove_if from the STL, and the predicate of remove_if requires a Unary Predicate. I hope to get the result of removing elements from the vector that equals "whereValue." So I'm trying to call my predicate in:
// Create EqualTemplate object
EqualTemplate equalTemplate = EqualTemplate(whereValueEntry, whereColIndex);
tables[tableName].table[tables[tableName].colNames[whereColName]].erase(
remove_if(tables[tableName].table[tables[tableName].colNames[whereColName]].begin(),
tables[tableName].table[tables[tableName].colNames[whereColName]].end(),
equalTemplate(tables[tableName].table[tables[tableName].colNames[whereColName]])), tables[tableName].table[tables[tableName].colNames[whereColName]].end());
My predicate is in a class called EqualTemplate:
// unary predicate class for use with remove_if
class EqualTemplate
{
private:
TableEntry whereValue;
int columnIndex;
public:
EqualTemplate(TableEntry &value, int &columnIndexIn) : whereValue(value), columnIndex(columnIndexIn) {}
bool operator()(vector<TableEntry>const &inputVector) { return inputVector[(uint32_t) columnIndex] == whereValue; }
};
The error I'm getting is as follows:
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__algorithm/remove_if.h:37:18: error: called object type 'bool' is not a function or function pointer
if (!__pred(*__i))
I'm confused because the bool operator() returns a bool, which is a function. Should I be writing the code differently? Thanks!
|
The error is quite clear. You are passing a bool as UnaryPredicate instead of a function - this is because you are calling the function and passing its return type, a boolean, to UnaryPredicate. Just pass equalTemplate, not equalTemplate(tables[tableName].table[tables[tableName].colNames[whereColName]]) - std::remove_if will call it for you.
|
74,439,909
| 74,439,948
|
Creating variable without defining the variables type class yet
|
class Component {
public:
Entity *parent = nullptr;
};
class Entity {
public:
Component components[25];
};
I am trying to create an entity component system, and above I have an issue. In the component class I am creating a pointer variable with the datatype being the "Entity" class, even though that gets defined later. Is there a way I can do this without an error occurring?
I tried using auto *parent = nullptr; but that doesn't work.
|
You need to declare Entity as a class, so the compiler knows what type this is.
class Entity;
Usually you would put these sorts of forward declarations in a generic header file, then define each class completely in its own Classname.cpp file.
|
74,440,760
| 74,440,933
|
How can i make my program do a specific calculation in a sequential IF statement
|
#include <stdio.h>
int main()
{
char ticketType;
int totalBill, studAmount, ticketType_R= 6500, ticketType_G= 7500;
printf("\nEnter your ticket type: ");
scanf("%c", &ticketType);
printf("\nEnter amount of students: ");
scanf("%d", &studAmount);
if(ticketType==ticketType_R)
{
totalBill==studAmount*6500;
printf("\nYour ticket type is R and your total bill is: %d", ticketType_R, totalBill);
}
if (ticketType==ticketType_G)
{
totalBill==studAmount*7500;
printf("\nYour ticket type is G and your total bill is: %d", ticketType_G, totalBill);
}
printf("\nThe amount of students attending are: %d ", studAmount);
return 0;
}
I tried the code that I made above and I was expecting it to
the type of ticket the user choose
print the amount of students attending
calculate the total amount by multiplying the amount of students by the price for the ticket
print the total amount
|
In your case, I believe you want to calculate value according to ticket type and the number of students.
That's how we can do it:
#include <stdio.h>
int main()
{
char ticketType;
int totalBill, studAmount, ticketType_R= 6500, ticketType_G= 7500;
printf("Enter the ticket type (R/G): "); // Input ticket type
scanf("%c", &ticketType);
// Use of Sequential if-else statement to calculate the total bill
if (ticketType == 'R')
{
printf("Enter the number of students: ");
scanf("%d", &studAmount);
totalBill = ticketType_R * studAmount;
printf("Your ticket type is R and your total bill is: %d", totalBill);
}
else if (ticketType == 'G')
{
printf("Enter the number of students: ");
scanf("%d", &studAmount);
totalBill = ticketType_G * studAmount;
printf("Your ticket type is G and your total bill is: %d", totalBill);
}
else
{
printf("Invalid ticket type");
}
// Total Students
printf("\nTotal number of students: %d", studAmount);
return 0;
}
As you are interested to do it in Python, that's how you will do it.
ticket_type = input("Enter the ticket type (R/G): ")
stud_amount = int(input("Enter the number of students: "))
if ticket_type == "R":
total_bill = 6500 * stud_amount
print("Your ticket type is R and your total bill is: ", total_bill)
elif ticket_type == "G":
total_bill = 7500 * stud_amount
print("Your ticket type is G and your total bill is: ", total_bill)
else:
print("Invalid ticket type")
print("Your Total number of students: ", stud_amount)
|
74,440,855
| 74,449,373
|
When to use x3::lit in Boost spirit
|
I am beginning with Boost Spirit x3 parsing library - and I'm very excited about it.
One thing unclear to me is when and why one should use x3::lit.
From what I understood, it's because we can not expect an expression like ']' >> double_ to be interpreted as intended within C++ syntactic rules.
But my interpretation seems incorrect, since the official documentation displays numerous examples of simple strings followed by the >> operator, and others instances where parenthesis and/or brackets have to be specified as lit(']')
What am I missing?
|
You can not generally expect '[' >> x to see the X3 expression overload.
Overload resolution depends on the types of both operands. Since '[' is char, there cannot be user-defined overloads. So in this case, only if x is already an x3 parser expression the x3 overload of operator>> will be found.
In generic code, if both operands are unknown you should use x3::as_parser instead of x3::lit because it will leave other types of expressions intact, but promotes string literals like you would expect:
auto combine(auto a, auto b) {
return x3::as_parser(a) >> x3::as_parser(b);
}
The mechanism for overload resolution at play in e.g. 'x' >> x3::double_ is ADL: https://en.cppreference.com/w/cpp/language/adl (Incidentally it's the same mechanism that makes std::cout << "Hello world\n" find the std::operator>> overload)
|
74,440,957
| 74,441,301
|
Crashing before calling unlink() on file created by mkstemp()
|
I am doing something like the following
auto tempFd = mkstemp(filePathTemplate);
// 1) write to temp file, on error, unlink()
// 2) sync temp file, on error, unlink()
// 3) close temp file, on error, unlink()
// 4) rename to implement an atomic write, on error unlink()
Here, what happens if the program crashes anywhere before step (4) has completely finished, but before the unlink executes? Will temporary files keep building up indefinitely if such crashes are frequent? If so, is there any way to avoid such files building up if the program keeps crashing in a loop?
Thanks!
|
The file will either be deleted or not. If it's not deleted it will persist till you either delete, or you reboot the system if you happen to write the file a tmpfs (memory) backed directory.
You write a log (fsync; local or remote) it that you are about to create a temporary file. When you start your program, you process the log and delete any temporary files you don't care about. If you crashes are frequent, and if you automatically restart your process, it will behave a like a fork storm (kill the box with load). Consider exponential delays, or if you cannot do that, implement a "dead letter" concept where troubled is moved aside.
Alternatively, create your temporary files in a special directory and remove whatever files in that directory. You may be interested in the program tmpreadper which you could invoke from a crontab. This will fail if you have sufficiently high rate of failure.
Consider using sqlite3.
|
74,441,348
| 74,441,458
|
why does my code not read or follow the if statements?
|
Why does my code not read or follow the if statements?
#include<iostream>
using namespace std;
int main (){
int sum = 0;
int integer;
while ((integer != -1) && (sum < 2000)){
int integer;
cout<<"Enter an integer: ";
cin>>integer;
if (integer == -1){
cout<<"Program was terminated.\n"<<"Your total sales are: "<<sum<<endl;
break;
}
else if (sum >= 2000) {
cout<<"Congratulations!"<<"Your total sales are: "<<sum<<endl;
break;
}
sum = sum + integer;
if (sum > 499){
cout<<"You're off to a good start!"<<endl;
}
if (sum > 999){
cout<<"You're halfway through!"<<endl;
}
else if (sum > 1499){
cout<<"You're almost there!"<<endl;
}
}
return 0;
}
Expected:
Input looks like:
Enter an interger: 350, 500,800, 500
Then the out should look like:
Enter an integer 350
" " 500
youre off to a good start
800
youre halfway through
500
Congratualations! Youre total sales are: 2150
Reality:
Enter an integer: 350
Enter an integer: 500
You're off to a good start!
Enter an integer: 800
You're off to a good start!
You're halfway through!
Enter an integer: 500
You're off to a good start!
You're halfway through!
|
you want only 1 branch to be entered, so you need a if else if chain.
if (sum >= 2000) {
std::cout << "Congratulations!" << "Your total sales are: " << sum << std::endl;
break;
}
else if (sum > 1499) {
std::cout << "You're almost there!" << std::endl;
}
else if (sum > 999) {
std::cout << "You're halfway through!" << std::endl;
}
else if (sum > 499) {
std::cout << "You're off to a good start!" << std::endl;
}
You have to start with the largest number to the smallest one, since if you go from smaller to larger, if a branch is entered it will always be the first branch.
while ((integer != -1) && (sum < 2000)){
this is wrong, as integer is not initialiazed and this is therefore undefined behaviour. In some cases it might never enter the while loop because integer holds some random garbage value that happens to be -1.
You can replace it with a simple while true loop:
while (true) {
since you are calling break; in the final branches anyway (this escapes the while loop). This will also fix the bug, that the loop would terminate before the final print outs.
int integer;
while ((integer != -1) && (sum < 2000)) {
int integer;
you just declared integer twice, the second one is not needed.
Full code:
#include <iostream>
int main() {
int sum = 0;
int integer;
while (true) {
std::cout << "Enter an integer: ";
std::cin >> integer;
if (integer == -1) {
std::cout << "Program was terminated.\n" << "Your total sales are: " << sum << std::endl;
break;
}
sum = sum + integer;
if (sum >= 2000) {
std::cout << "Congratulations!" << "Your total sales are: " << sum << std::endl;
break;
}
else if (sum > 1499) {
std::cout << "You're almost there!" << std::endl;
}
else if (sum > 999) {
std::cout << "You're halfway through!" << std::endl;
}
else if (sum > 499) {
std::cout << "You're off to a good start!" << std::endl;
}
}
}
read Why is "using namespace std;" considered bad practice?
|
74,441,894
| 74,445,181
|
Compute shader can't get result image
|
I am using the compute shader to get a column of colors to match the conditions and I want to get the results for further processing. I want to get the output data in image1D imgOutput, but get_img can't get anything, did I do something wrong?
the texture in the first block has been generated before.
Shader spriteRowProgram, spriteColumnProgram;
unsigned int resultTexture = 0;
const std::string path = found::utils::Environment::GetRunPath();
const std::string sprite_row_path = path + "shaders/glfw_sprite_row.comp";
spriteRowProgram = Shader(sprite_row_path);
std::vector<GLfloat> get_img(qMax(TEX_WIDTH, TEX_HEIGHT) * 4);
glGenTextures(1, &resultTexture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_1D, resultTexture);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA32F, qMax(TEX_WIDTH, TEX_HEIGHT), 0, GL_RGBA, GL_FLOAT, get_img.data());
glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, texture);
spriteRowProgram.use();
glUniform1i(1, 1);
glBindImageTexture(1, texture, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA32F);
glUniform1i(0, 0);
glBindImageTexture(0, resultTexture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);
glClear(GL_COLOR_BUFFER_BIT);
spriteRowProgram.setInt("input_width", TEX_WIDTH);
spriteRowProgram.setInt("input_height", TEX_HEIGHT);
glDispatchCompute(TEX_WIDTH, 1, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
#version 430 core
layout (local_size_x = 1, local_size_y = 1) in;
layout(rgba32f, location = 0, binding = 0) uniform writeonly image1D imgOutput;
// texture samplers
layout(rgba32f, location = 1, binding = 1) uniform readonly image2D inputImage;
uniform int input_width;
uniform int input_height;
void main()
{
vec4 baseColor = imageLoad(inputImage, ivec2(0, 0));
bool alpha = baseColor.w == 1;
bool success = true;
for (int i = 0; i <= input_height; ++i)
{
vec4 current = imageLoad(inputImage, ivec2(gl_GlobalInvocationID.x, i));
if (alpha) {
if (current.w > 0.99) continue;
else {
success = false;
break;
}
} else {
vec4 difference = baseColor - current;
success = abs(difference.x) < 0.01 && abs(difference.y) < 0.01 && abs(difference.z) < 0.01;
if (success) continue;
else {
break;
}
}
}
if (success) baseColor = ivec4(0.1, 0.1, 0.1, 0.1);
else baseColor = ivec4(1.0, 1.0, 1.0, 1.0);
imageStore(imgOutput, int(gl_GlobalInvocationID.x), baseColor);
}
|
One issue might be that if you want to access images after the compute shader, the argument for glMemoryBarrier should be GL_SHADER_IMAGE_ACCESS_BARRIER_BIT and not GL_SHADER_STORAGE_BARRIER_BIT.
So
spriteRowProgram.setInt("input_width", TEX_WIDTH);
spriteRowProgram.setInt("input_height", TEX_HEIGHT);
glDispatchCompute(TEX_WIDTH, 1, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
should really be
spriteRowProgram.setInt("input_width", TEX_WIDTH);
spriteRowProgram.setInt("input_height", TEX_HEIGHT);
glDispatchCompute(TEX_WIDTH, 1, 1);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
|
74,442,281
| 74,488,642
|
Deadlocked program using pthread condition variables, critical sections [C++]
|
What I'm trying to do is have each thread copy information from a struct in main using a critical section before main changes the struct for other threads.
#include <iostream>
#include <pthread.h>
using namespace std;
struct foo
{
public:
int var;
int *turn;
int index;
pthread_mutex_t *bsem;
pthread_cond_t *waitTurn;
};
void *threadFunc(void *arg) {
int var;
foo *workingVar = (foo *)arg;
pthread_mutex_lock(workingVar->bsem);
while (*workingVar->turn != workingVar->index)
pthread_cond_wait(workingVar->waitTurn, workingVar->bsem);
var = workingVar->var;
*workingVar->turn++;
pthread_cond_broadcast(workingVar->waitTurn);
pthread_mutex_unlock(workingVar->bsem);
cout << var << endl;
return nullptr;
}
int main() {
int turn = 0, NTHREADS = 5;
foo mainStruct;
pthread_mutex_t bsem;
pthread_mutex_init(&bsem, NULL);
pthread_cond_t waitTurn = PTHREAD_COND_INITIALIZER;
mainStruct.bsem = &bsem;
mainStruct.waitTurn = &waitTurn;
mainStruct.turn = &turn;
pthread_t tid[NTHREADS];
for (int i = 0; i < NTHREADS; i++) {
mainStruct.index = i;
mainStruct.var = i;
pthread_create(&tid[i], nullptr, threadFunc, &mainStruct);
}
for (int i = 0; i < NTHREADS; i++)
pthread_join(tid[i], NULL);
}
The code above is from a thread function. I'm trying to make threads wait until it is their 'turn' using pthread_cond_wait, and then once the condition is true, the struct info passed from main will be copied into local variables and will increment the turn and exit the critical section (also not using global variables, so mutex and condition variable is passed using a pointer through the struct). Turn is initialized to 0, and index is the thread number (in the order of which it was created).
This process is deadlocked, and times out.
Please let me know if any more context/information is needed, this is my first Stack Overflow question.
|
I see race condition on mainStruct.index. Main thread modifies it without lock and multiple threads are accessing it under a lock. So if first thread starts fast it will interact with your loop spawning threads.
Looks like you plan was to have multiple instances of Foo, but you have one. So imagine scenario:
Main thread reaches first join
Other threads were created, but didn't start ruinng yet
At that point value of mainStruct.index is 4!
First thread starts executing and acqurie lock.
turn is 0 and workingVar->index is 4 (see point 3)
So threads enters pthread_cond_wait and waits
Next thread executes same as points 4-6
Same for other threads
All side threads are in waiting state
All threads are waiting no one has called pthread_cond_broadcast
condition *workingVar->turn != workingVar->index is always true
Also your code is written in C not in C++. The only C++ is use of std::cout!. Try rewrite this using std::thread and it will fix itself (if you pas arguments by values).
Here is my C++ version
|
74,442,721
| 74,442,864
|
Pass a lambda which captures a unique_ptr to another function
|
I want to pass a mutable lambda which captures a unique_ptr to another function as shown in the code snippet below.
#include <functional>
#include <memory>
#include <iostream>
struct Adder {
Adder(int val1, std::unique_ptr<int> val2) : val1_(val1), val2_(std::move(val2)) {
}
int Add() {
return val1_ + *val2_;
}
int val1_;
std::unique_ptr<int> val2_;
};
void CallAdder(std::function<int ()> func) {
std::cout << func() << "\n";
}
int main() {
auto ptr = std::make_unique<int>(40);
int byRef = 2;
auto lam = [&, p = std::move(ptr)]() mutable
{
return Adder(byRef, std::move(p)).Add();
};
CallAdder(std::move(lam));
}
Above code gives me a deleted copy constructor error for the lambda as follows.
$ clang++-14 -o lam lambda.cc
In file included from lambda.cc:2:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/functional:59:
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/std_function.h:161:10: error: call to implicitly-deleted copy constructor of '(lambda at lambda.cc:25:16)'
new _Functor(*__source._M_access<const _Functor*>());
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/std_function.h:196:8: note: in instantiation of member function 'std::_Function_base::_Base_manager<(lambda at lambda.cc:25:16)>::_M_clone' requested here
_M_clone(__dest, __source, _Local_storage());
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/std_function.h:283:13: note: in instantiation of member function 'std::_Function_base::_Base_manager<(lambda at lambda.cc:25:16)>::_M_manager' requested here
_Base::_M_manager(__dest, __source, __op);
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/std_function.h:611:33: note: in instantiation of member function 'std::_Function_handler<int (), (lambda at lambda.cc:25:16)>::_M_manager' requested here
_M_manager = &_My_handler::_M_manager;
^
lambda.cc:30:15: note: in instantiation of function template specialization 'std::function<int ()>::function<(lambda at lambda.cc:25:16), void, void>' requested here
CallAdder(std::move(lam));
^
lambda.cc:25:20: note: copy constructor of '' is implicitly deleted because field '' has a deleted copy constructor
auto lam = [&, p = std::move(ptr)]() mutable
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/unique_ptr.h:468:7: note: 'unique_ptr' has been explicitly marked deleted here
unique_ptr(const unique_ptr&) = delete;
^
I also tried passing lambda as a reference as per cannot pass deleted lambda function with move? but I was getting a type error which complains about it not being able to typecheck the lambda against the std::function in the CallAdder signature. How would I fix this error?
|
You can template CallAdder on a function parameter.
[Demo]
#include <functional>
#include <iostream>
#include <memory>
struct Adder {
Adder(int val1, std::unique_ptr<int> val2)
: val1_(val1), val2_(std::move(val2)) {}
int Add() { return val1_ + *val2_; }
int val1_;
std::unique_ptr<int> val2_;
};
template <typename F>
void CallAdder(F&& func) { std::cout << std::forward<F>(func)() << "\n"; }
int main() {
auto ptr = std::make_unique<int>(40);
int byRef = 2;
auto lam = [&byRef, p = std::move(ptr)]() mutable {
return Adder(byRef, std::move(p)).Add();
};
CallAdder(std::move(lam));
}
// Outputs: 42
Or just:
[Demo]
#include <functional>
#include <iostream>
#include <memory>
struct Adder {
Adder(int val1, std::unique_ptr<int> val2)
: val1_(val1), val2_(std::move(val2)) {}
int Add() { return val1_ + *val2_; }
int val1_;
std::unique_ptr<int> val2_;
};
void CallAdder(std::function<int()> func) { std::cout << func() << "\n"; }
int main() {
auto ptr = std::make_unique<int>(40);
int byRef = 2;
auto lam = [&]() {
return Adder(byRef, std::move(ptr)).Add();
};
CallAdder(lam);
}
|
74,443,349
| 74,443,441
|
how to print elements of a vector of type Person class in c++
|
I created a class called person with two members name and age then I created two objects of that
class p1 and p2 and then I added them to a vector. I tried then to print them but could not.
this my code:
class Person{
public:
string name;
int age;
};
int main(){
Person p;
vector <Person> vector;
p.name = "Vitalik";
p.age = 29;
Person p2;
p2.name = "Bueterin";
p2.age = 50;
vector.push_back(p);
vector.push_back(p2);
for(int i = 0; i < vector.size(); i++){
cout << vector[i] << endl;
}
return 0;
}
I tried multiple ways to loop through the vector and print the elements but I keep getting this message:
error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'std::__vector_base<Person, std::allocator<Person> >::value_type' (aka 'Person'))
cout << vector[i] << endl;
|
You can implement operator<< or just write something like this:
cout << vector[i].name << ": " << vector[i].age << endl;
cout doesn't know how to print this object by default.
|
74,443,625
| 74,451,693
|
Split text with array of delimiters
|
I want a function that split text by array of delimiters. I have a demo that works perfectly, but it is really really slow. Here is a example of parameters.
text:
"pop-pap-bab bob"
vector of delimiters:
"-"," "
the result:
"pop", "-", "pap", "-", "bab", "bob"
So the function loops throw the string and tries to find delimeters and if it finds one it pushes the text and the delimiter that was found to the result array, if the text only contains spaces or if it is empty then don't push the text.
std::string replace(std::string str,std::string old,std::string new_str){
size_t pos = 0;
while ((pos = str.find(old)) != std::string::npos) {
str.replace(pos, old.length(), new_str);
}
return str;
}
std::vector<std::string> split_with_delimeter(std::string str,std::vector<std::string> delimeters){
std::vector<std::string> result;
std::string token;
int flag = 0;
for(int i=0;i<(int)str.size();i++){
for(int j=0;j<(int)delimeters.size();j++){
if(str.substr(i,delimeters.at(j).size()) == delimeters.at(j)){
if(token != ""){
result.push_back(token);
token = "";
}
if(replace(delimeters.at(j)," ","") != ""){
result.push_back(delimeters.at(j));
}
i += delimeters.at(j).size()-1;
flag = 1;
break;
}
}
if(flag == 0){token += str.at(i);}
flag = 0;
}
if(token != ""){
result.push_back(token);
}
return result;
}
My issue is that, the functions is really slow since it has 3 loops. I am wondering if anyone knows how to make the function faster. I am sorry, if I wasn't clear enough my english isn't the best.
|
It might be a good idea to use boost expressive. It is a powerful tool for various string operations more than struggling with string::find_xx and self for-loop or regex.
Concise explanation:
+as_xpr(" ") is repeated match more than 1 like regex and then prefix "-" means
shortest match.
If you define regex parser as sregex rex = "(" >> (+_w | +"_") >> ":" >> +_d >> ")", it would match (port_num:8080). In this case, ">>" means the concat of parsers and (+_w | +"_") means that it matches character or "_" repeatedly.
#include <vector>
#include <string>
#include <iostream>
#include <boost/xpressive/xpressive.hpp>
using namespace std;
using namespace boost::xpressive;
int main() {
string source = "Nigeria is a multi&&national state in--habited by more than 2;;50 ethnic groups speak###ing 500 distinct languages";
vector<string> delimiters{ " ", " ", "&&", "-", ";;", "###"};
vector<sregex> pss{ -+as_xpr(delimiters.front()) };
for (const auto& d : delimiters) pss.push_back(pss.back() | -+as_xpr(d));
vector<string> ret;
size_t pos = 0;
auto push = [&](auto s, auto e) { ret.push_back(source.substr(s, e)); };
for_each(sregex_iterator(source.begin(), source.end(), pss.back()), {}, [&](smatch const& m) {
if (m.position() - pos) push(pos, m.position() - pos);
pos = m.position() + m.str().size();
}
);
push(pos, source.size() - pos);
for (auto& s : ret) printf("%s\n", s.c_str());
}
Output is splitted by multiple string delimiers.
Nigeria
is
a
multi
national
state
in
habited
by
more
than
2
50
ethnic
groups
speak
ing
500
distinct
languages
|
74,443,994
| 74,444,587
|
How to pass a pointer argument to std::format?
|
In the following code, when the first argument is an int and another a pointer casted to void*, the code compiles:
AYAPI_API int AYBlitBuffer(int a1, int a2, int* a3, int* a4)
{
Log(std::format("@{}: a1 = {}, a2 = {}, a3 = {}, a4 = {}", __FUNCTION__, a1, a2, static_cast<void*>(a3), static_cast<void*>(a4)));
return 0;
}
If, however, passing a unique argument that is a pointer, the code does not compile:
AYAPI_API int AYRenderPrim(int *a1)
{
Log(std::format("@{}: a1 = {:#010x}", __FUNCTION__, static_cast<void*>(a1)));
return 0;
}
The actual error:
error C7595: 'std::_Basic_format_string<char,const char (&)[13],void *>::_Basic_format_string': call to immediate function is not a constant expression
How can one pass both integers and pointers to integers to be formatted by std::format?
|
The error you are seeing has nothing to do with the presence or absence of any int arguments amongst the parameters to the call to std::format. (Try changing the format string in your first snippet so that it ends with a4 = {:#010x} in place of a4 = {} and you will see the same error message, there.)
Rather, the error – albeit cryptic – occurs because the format specifier you provide is not valid for a pointer argument. The # specifer is only valid for integer or floating-point arguments (as also the leading 0 and the trailing x?). (Possibly useful cppreference page.)
So, in your case, if you want to specify such a format for a pointer value, you should cast that pointer to a suitable integer type (intptr_t or uintptr_t are likely good candidates) rather than to a void*:
AYAPI_API int AYRenderPrim(int* a1)
{
Log(std::format("@{}: a1 = {:#010x}", __FUNCTION__, reinterpret_cast<intptr_t>(a1)));
return 0;
}
|
74,444,442
| 74,444,696
|
How to convert vector<vector<int>>to int**?
|
vectoris easy to obtain int* through vector::data(), so how to convert vector<vector>to int**?
int main(int argc, char *argv[])
{
std::vector<std::vector<int>> temp {{1,2,3},{4,5,6}};
int **t;
t = reinterpret_cast<int **>(std::data(temp));
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
std::cout << t[i][j] << " ";
}
}
}
// out : 1 2 3 0 0 0
It's obviously wrong.
|
There is a simple "trick" to create the pointer that you need, as a temporary workaround while the code is being refactored to handle standard containers (which is what I really recommend that you should do).
The vectors data function returns a pointer to its first element. So if we have a std::vector<int> object, then its data function will return an int*. That puts us about halfway to the final solution.
The second half comes by having a std::vector<int*>, and using its data function to return an int**.
Putting this together, we create a std::vector<int*> with the same size as the original std::vector<...> object, and then initialize all elements to point to the sub-vectors:
std::vector<std::vector<int>> temp;
// ...
// Create the vector of pointers
std::vector<int*> pointer_vector(temp.size());
// Copy the pointers from the sub-vectors
for (size_t i = 0; i < temp.size(); ++i)
{
pointer_vector[i] = temp[i].data();
}
After the above loop, then you can use pointer_vector.data() to get the int** pointer you need.
Until you have refactored the code, you could put this in an overloaded function that does the conversion and calls the actual function:
// The original function
void some_function(int**);
// Creates a vector of pointers, and use it for the
// call of `some_function(int**)`
void some_function(std::vector<std::vector<int>> const& actual_vector);
|
74,444,665
| 74,445,757
|
How to initialize a static array within a c-style struct by an existing static array?
|
I'm currently doing c++ with OpenCL, where a c-style struct is required to carry configuration information from the c++ host to the OpenCL kernel. Given that dynamically allocated arrays are not guaranteed to be supported by every OpenCL implementation, I must ensure every array accessible by the kernel code be static-sized. However, I run into weird errors when initializing static arrays within a c-style struct.
The error could be reproduced by the following PoC:
#include <cstring>
#include <string>
#define ID_SIZE 16
struct conf_t {
const unsigned int a;
const unsigned int b;
const unsigned char id[ID_SIZE];
};
int main() {
const std::string raw_id("0123456789ABCDEF");
unsigned char id[ID_SIZE];
memcpy(id,raw_id.c_str(),ID_SIZE);
struct conf_t conf = {10,2048,id};
}
And the following error:
poc.cc: In function ‘int main()’:
poc.cc:15:39: error: array must be initialized with a brace-enclosed initializer
15 | struct conf_t conf = {10,2048,id};
| ^~
It's true that I could remove the const keyword in the struct and get rid of the stack variable id, where &(conf.id) could be the first parameter of memcpy. However, I'd like to keep the immutability of fields in the conf struct, which enables the compilers to check undesired modifications.
For my understanding, structs in c should have the following memory layout:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| a |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| b |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ id +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Given the stack variable id is also with static size, I'm confused why the c++ compiler still looks for a brace-enclosed initializer even if id is already a static-sized array.
|
If you want to copy the entire string, you have to use memcopy into conf.id (or strncpy if it is guaranteed to be a zero-terminated string). Unfortunately this means that the id in conf_t cannot be const anymore:
#include <iostream>
#include <cstring>
#include <string>
#define ID_SIZE 16
struct conf_t
{
const unsigned int a;
const unsigned int b;
unsigned char id[ID_SIZE];
};
int main()
{
const std::string raw_id("0123456789ABCDE");
conf_t conf = {10, 2048, {0}};
memcpy(conf.id, raw_id.c_str(), ID_SIZE); // <- memcopy from the string into conf.id
std::cout << conf.id << '\n';
std::cout << std::boolalpha;
std::cout << std::is_pod<conf_t>::value << '\n';
}
On the other hand, if conf_t.id must be const, then I believe you must use a compile-time constant initialization in order to keep conf_t a POD class:
struct conf_t
{
const unsigned int a;
const unsigned int b;
const unsigned char id[ID_SIZE];
};
int main()
{
conf_t conf = {10, 2048, "0123456789ABCDE"};
...
It is also possible to use a template constructor to turn a dynamic array into an initializer-list. This will enable you to initialize a const c-array with dynamic data, but it adds a constructor to conf_t which means that it no longer is a POD class.
#include <iostream>
#include <cstring>
#include <string>
#include <utility>
#define ID_SIZE 16
struct conf_t
{
const unsigned int a;
const unsigned int b;
const unsigned char id[ID_SIZE];
conf_t(const unsigned int a,
const unsigned int b,
const unsigned char (&arr)[ID_SIZE])
: conf_t(a, b, arr, std::make_index_sequence<ID_SIZE>())
{
}
private:
template <std::size_t... Is>
conf_t(const unsigned int a,
const unsigned int b,
const unsigned char (&arr)[ID_SIZE], std::index_sequence<Is...>)
: a{a},
b{b},
id{arr[Is]...}
{
}
};
int main()
{
const std::string raw_id("0123456789ABCDE");
unsigned char id[ID_SIZE];
memcpy(id, raw_id.c_str(), ID_SIZE);
conf_t conf = {10, 2048, id};
std::cout << conf.a << '\n';
std::cout << conf.b << '\n';
std::cout << conf.id << '\n';
std::cout << std::boolalpha;
std::cout << std::is_pod<conf_t>::value << '\n';
}
It is possible that I have missed something though, so I welcome any corrections.
|
74,445,620
| 74,446,144
|
Implementing move semantics in the legacy C++ class
|
I am working on a legacy application with a class named Point3D as shown below...
template <class T>
class Point3D final
{
T values[3];
public:
Point3D();
Point3D(T x, T y, T z);
explicit Point3D(const T value);
Point3D(const Point3D& point);
explicit Point3D(const Point2D<T>& point);
~Point3D();
};
This class is getting used in many places as vector<Point3D<double>>. The size of the vector is > 10^5.
Also, the legacy code passes this vector as a value and returns by value. This is making the application very slow.
Also in many places, we have similar codes as shown below...
for(auto i: n){ // This loop runs for 10^4 times
Point3D<double> vpos;
vpos[X_COORDINATE] = /*Some calculation*/;
vpos[Y_COORDINATE] = /*Some calculation*/;
vpos[Z_COORDINATE] = /*Some calculation*/;
Positions.push_back(vpos);
}
To improve the performance, I plan to modify the Point3D class to use move semantics as shown below...
template <class T>
class Point3D final {
T* values;
public:
Point3D() {
values = new T[3];
}
Point3D(T x, T y, T z) {
values = new T[3];
}
explicit Point3D(const T value) {
values = new T[3];
}
Point3D(const Point3D& point) {
values = new T[3];
}
~Point3D() {
delete[] values;
}
T operator [] (qint64 coordinate) const { return values[coordinate]; }
T& operator [] (qint64 coordinate) { return values[coordinate]; }
Point3D& operator = (const Point3D& point) {
...
return *this;
}
Point3D(Point3D&& other) noexcept : values(other.values)
{
other.values = nullptr;
}
Point3D& operator=(Point3D&& other) noexcept
{
using std::swap;
swap(*this, other);
return *this;
}
};
I am new to move semantics, please let me know any other ways to improve the performance.
Thanks
|
Also, the legacy code passes this vector as a value and returns by value. This is making the application very slow.
Your suggested modifications will make this worse in general. The cost of copying or moving your original Point3D is very small if T is a simple type like double. It will just copy three double values. If T is a complex type, then as the other answer suggests, removing the declared destructor and copy constructor will cause move semantics to be implemented correctly automatically. (This is also known as the "rule-of-zero", letting all special member functions be implemented implicitly.)
If your problem are many copies of a vector of the type, move semantics on the type will however not help you at all. Copying the vector will still require copying all elements. Moving will not be sufficient.
You need to adjust your code at the use site of these vectors. For example, if you are passing a vector like this by-value:
void f(vector<Point3D<double>>);
void g() {
vector<Point3D<double>> v;
// fill v
f(v);
}
Then this will make an unnecessary copy of the vector. It is unnecessary because v's data is not required anymore after the call to f in g. So it can be moved instead of copied into the function:
void g() {
vector<Point3D<double>> v;
// fill v
f(std::move(v));
}
This will move the vector, not the Point3D<double>'s. Moving a vector is a constant time operation, no matter whether or not move semantics are implemented for the element type. It won't copy or move any element.
If however v's state is used in g after the call, then you can't use move semantics directly, because move semantics will cause the state to be lost. In that case you need to rethink the design of the function and consider e.g. passing by const-reference instead.
(Note however that you should not use std::move if you return the vector. E.g. return std::move(v); should be return v; instead. Move is implicit on return statements that just return a local variable directly by name and doing the implicit std::move call will inhibit copy elision which in certain situations will eliminate copy/moves completely.)
|
74,446,006
| 74,446,514
|
How load two QML merging two project
|
I'm merging two QML\Qt project into new one and I've a problem with *.qml files.
In original projects I've a main.qml with timer, proprieties,... and a loader for bring-up the custon *.qml, to summarize: 2 folder (QML_10 and QML_15), 2 main.qml and several other qml files.
I would have a sinle project which is able to load one main or other in according to arcv[] C++ parameter.
in my C++ code :
QUrl url(QStringLiteral("qrc:/main.qml"));
if (atoi(argv[1]) == ROLE1)
url.setUrl(QString("/QML_10/main.qml"))
else if (atoi(argv[1]) == ROLE2)
url.setUrl(QString("/QML_15/main.qml"))
else
printf("Error\n")
When I run the application I'm able to detect the right role but the setYrl doesn't work with error :
file:///QML_1/main.qml: No such file or directory
The Qt project structure is :
|
With setUrl you replace the complete content of QUrl, leading to a URL without scheme, upon which the default file: scheme is assumed. You should either put qrc: in front, or use setPath.
Alternatively you could use setScheme("qrc") afterwards.
|
74,446,181
| 74,446,275
|
Regular expression missing the pattern match
|
I am trying to match a pattern with my input using regular expression .
I am trying to match the following string
00010_mesh_fbx_low_pileOfStoneAtWonwonsaTemple.fbx
using the following regular expression
std::regex("^[0-9]+_mesh_fbx_low_[a-z][A-Z][0-9].(?:fbx|glb|obj)"))
But I do not get a match for the input string
|
[a-z][A-Z][0-9]. matches a sequence of four chars: a lowercase ASCII letter, then an uppercase ASCII letter, then an ASCII digit and then any char other than line break chars.
You can fix your regex by using
std::regex(R"(^[0-9]+_mesh_fbx_low_[a-zA-Z0-9]+\.(?:fbx|glb|obj))")
std::regex(R"(^[0-9]+_mesh_fbx_low_\w+\.(?:fbx|glb|obj))")
where [a-zA-Z0-9]+ matches one or more ASCII alphanumeric chars, or \w+ that matches one or more ASCII alphanumeric or underscore chars.
|
74,446,197
| 74,446,291
|
C++ How does if (system("CLS") {system("clear)} work
|
C++ How does this work
if (system("cls"))
{
system("clear")
}
I was trying to find a cross-platform way to clear console in c++
and I remembered some code with this syntax so I tried it and it worked
but I want to know how it works like does it return an error or something
if the command was not found
sorry if it was a stupid question
|
cls and clear are terminal/command prompt commands used to clear the screen.
system is a c++ command used to interact with the cmd/terminal directly. It returns 0 if a command was completed successfully.
In this case, if cls fails to clear the screen (in other words, the system command returns something other than 0) then we issue the clear command via system.
One of those commands will work on the OS that the app is being run on.
|
74,446,298
| 74,446,467
|
need to parse json file and put all subfields into 2-level array
|
JSON:
{
"media": {
"Test1": "https://storage.tst",
"Test2": "https://storage.tst"
}
}
I need to put those keys (Test) and it's value in to 2-level array in cycles
Like @sehe offered, I used next code:
#include <boost/json.hpp>
//#include <boost/json/src.hpp> // for header-only
//(in the another file I already included <boost/json/src.hpp>)
std::map<std::string, std::string> not_an_array;
for (auto& kvp : sample.at("media").as_object()) {
not_an_array.emplace(kvp.key(), kvp.value().as_string());
}
But I got an error "sample" is undefined. I suppose, I should include some json header for it. But, I have included it.
C++11.
|
You should use the other lines of code that @sehe provided as well:
auto sample = boost::json::parse(R"(
{
"media": {
"Test1": "https://storage.tst",
"Test2": "https://storage.tst"
}
})");
They conveniently included a live demo:
Live On Coliru
#include <boost/json/src.hpp> // for header-only
#include <fmt/ranges.h>
#include <iostream>
#include <map>
namespace json = boost::json;
int main() {
json::value sample = json::parse(R"(
{
"media": {
"Test1": "https://storage.tst",
"Test2": "https://storage.tst"
}
})");
std::map<std::string, std::string> not_an_array;
for (auto& kvp : sample.at("media").as_object()) {
not_an_array.emplace(kvp.key(), kvp.value().as_string());
}
fmt::print("not_an_array: {}\n", not_an_array);
}
But C++11?
They also included a C++11 example:
Live On Compiler Explorer
#include <boost/json/src.hpp> // for header-only
#include <iostream>
#include <map>
namespace json = boost::json;
int main() {
json::value sample = json::parse(R"(
{
"media": {
"Test1": "https://storage.tst",
"Test2": "https://storage.tst"
}
})");
std::map<json::string_view, json::string_view> not_an_array;
for (json::object::value_type& kvp : sample.at("media").as_object()) {
json::string_view k = kvp.key();
json::value& v = kvp.value();
not_an_array.emplace(k, v.as_string());
}
for (auto& pair : not_an_array) {
std::cout << pair.first << " -> " << pair.second << "\n";
}
}
|
74,446,359
| 74,452,180
|
Creating Win32 controls in a separate class
|
I have a Window class and a MainMenu class. In the Window class, I create the window itself, and in the MainMenu class I create the controls for the Window (like in C# with form and user-control).
Do I need to define, let's say #define EXIT_BUTTON 1, in Window.cpp and MainMenu.cpp for button events to work, or is there a better way?
exit = CreateWindow(L"Button", L"Exit", style, monitor.right / 2 - 100, 150, 200, 100, m_hWnd, **HMENU(EXIT_BUTTON)**, NULL, NULL);
Window.cpp
#include "Window.h"
#define EXIT_BUTTON 1
MainMenu* mainMenu1;
Window::Window() : m_hInst(GetModuleHandle(nullptr)) //creates the window
{
WNDCLASS wc = {};
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hInstance = m_hInst;
wc.lpszClassName = ClassName;
wc.lpfnWndProc = WindProc;
RegisterClass(&wc);
DWORD style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
GetWindowRect(GetDesktopWindow(), &monitor);
m_hWnd = CreateWindow(ClassName, WindowTitle, style, 0, 0, 0, 0, NULL, NULL, NULL, NULL);
mainMenu1 = new MainMenu(m_hWnd, monitor);
ShowWindow(m_hWnd, SW_MAXIMIZE);
}
Window::~Window()
{
UnregisterClass(ClassName, m_hInst);
delete mainMenu1;
}
LRESULT CALLBACK WindProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) // gets input from user
{
switch (msg) {
case WM_CREATE:
AddControls();
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_COMMAND:
switch (wp) {
case EXIT_BUTTON:
PostQuitMessage(0);
break;
}
case WM_WINDOWPOSCHANGED:
std::cout << "1";
break;
default:
return DefWindowProcW(hwnd, msg, wp, lp);
}
return 1;
}
bool Window::ProcessMessage()
{
MSG msg = {};
while (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) {
if (msg.message == WM_QUIT)
return false;
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return true;
}
void AddControls()
{
mainMenu1->Initialize();
}
MainMenu.cpp
#include "MainMenu.h"
#define EXIT_BUTTON 1
MainMenu::MainMenu(HWND hWnd, RECT monitor)
{
this->monitor = monitor;
m_hWnd = hWnd;
}
MainMenu::~MainMenu()
{
}
void MainMenu::Initialize()
{
DWORD style = WS_VISIBLE | WS_CHILD | SS_CENTER;
title = CreateWindow(L"static", L"Welcome", style, monitor.right / 2 - 100, 100, 200, 100, m_hWnd, NULL, NULL, NULL);
SendMessage(title, WM_SETFONT, WPARAM(CreateFont(50, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Arial")), true);
exit = CreateWindow(L"Button", L"Exit", style, monitor.right / 2 - 100, 150, 200, 100, m_hWnd, HMENU(EXIT_BUTTON), NULL, NULL);
}
void MainMenu::Hide()
{
}
void MainMenu::Show()
{
}
|
You should create app_common.h header file and write define to it.
app_common.h
#pragma once
#define EXIT_BUTTON 1
and update your Window.cpp
#include "app_common.h"
#include "Window.h"
....
and then update your MainMenu.cpp
#include "app_common.h"
#include "MainMenu.h"
.....
|
74,446,648
| 74,446,949
|
Function pointers, conversions and comparisons
|
From what I get, casting function pointers to different types is allowed by the C++ standard (as long as one never invokes them):
int my_func(int v) { return v; }
int main() {
using from_type = int(int);
using to_type = void(void);
from_type *from = &my_func;
to_type *to = reinterpret_cast<to_type *>(from);
// ...
}
Moreover, there is no UB if I cast the pointer back to its original type and invoke it.
So far, so good. What about the following then?
const bool eq = (to == reinterpret_cast<to_type *>(my_func));
That is, does the address hold too after the conversion or this isn't guaranteed by the standard?
Intuitively, I don't see why it shouldn't. However, there are many UBs in the standard that betray my intuition. So better ask.
While this is irrelevant to the question, a possible scenario is when one goes hard on type erasure. If the address holds, something can be done without having to know the original function type.
|
From [expr.reinterpret.cast].6 (emphasis mine):
A function pointer can be explicitly converted to a function pointer of a different type.
[...]
Except that converting a prvalue of type “pointer to T1” to the type
“pointer to T2” (where T1 and T2 are function types) and back to its
original type yields the original pointer value, the result of such a
pointer conversion is unspecified.
So, the standard explicitly allows casting function pointers to different FP types and then back. This is an exception to the general rule that reinterpret_casting function pointers is unspecified.
In my understanding, that means to == reinterpret_cast<to_type *>(my_func) need not necessarily be true.
|
74,447,077
| 74,447,297
|
Sort a list of objects by property in C++ using the standard list
|
I am currently trying to sort a list of objects in this case students, based on their grades, student number, name, etc.
listOfStudents.sort([](const Students& student1, const Students& student2)
{
if (student1.getStudentNumber() == student2.getStudentNumber())
return student1 < student2;
return student1.getStudentNumber() < student2.getStudentNumber();
});
This is the code I am currently using to sort the list based on their student number but it points an error to the student1 and student2 saying "The object has type qualifiers that are not compatible".
Here is the code for the Student Class:
class Students {
int studentNumber;
string studentName;
int grade1;
int grade2;
int grade3;
int grade4;
int grade5;
int total;
public:
void setStudent(int number, string name, int g1, int g2, int g3, int g4, int g5, int total) {
this->studentNumber = number;
this->studentName = name;
this->grade1 = g1;
this->grade2 = g2;
this->grade3 = g3;
this->grade4 = g4;
this->grade5 = g5;
this->total = total;
}
int getStudentNumber() {
return this->studentNumber;
}
string getStudentName() {
return this->studentName;
}
int getGrade1() {
return this->grade1;
}
int getGrade2() {
return this->grade2;
}
int getGrade3() {
return this->grade3;
}
int getGrade4() {
return this->grade4;
}
int getGrade5() {
return this->grade5;
}
int getTotal() {
return this->total;
}
};
and this is the implementation part
list <Students> listOfStudents;
Students students;
The above codes are currently producing errors about the list type qualifiers etc.
Did I miss something? Im sure I did. Thank you in advance for relieving my idiocy.
|
int getStudentNumber() {
return this->studentNumber;
}
should be
int getStudentNumber() const {
return this->studentNumber;
}
and the same for all the other getters in your code.
|
74,448,142
| 74,448,328
|
Lambda to function using generalized capture impossible?
|
A lambda can be easily converted to std::function though this seems to be impossible when the lambda uses generalized capture with a unique_ptr. Likely an underlying std::move is missing. Is there a workaround for this or is this a known issue?
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
int main()
{
auto lambdaGeneralizedCaptureOk = [t = std::make_unique<int>(1)]()
{
std::cout << *t << std::endl;
};
lambdaGeneralizedCaptureOk();
// error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete]’
std::function<void()> lambdaToFunctionGeneralizedCaptureNok = [t = std::make_unique<int>(2)]()
{
std::cout << *t << std::endl;
};
lambdaToFunctionGeneralizedCaptureNok();
return 0;
}
|
Is there a workaround for this or is this a known issue?
std::function requires that the underlying callable must be copyable, since the lambda object in your example is move-only, this is ill-formed.
It's worth noting that C++23 introduced move_only_function, which does exactly what you need
std::move_only_function<void()> lambdaToFunctionGeneralizedCaptureNok =
[t = std::make_unique<int>(2)]() {
std::cout << *t << std::endl;
};
Demo
|
74,448,716
| 74,449,294
|
How to select a huge string variable in VS Code?
|
So I have this huge line-by-line std::string variable which is about 58 thousand lines.
How could I select my entire variable? By clicking and dragging I think it takes about 5 minutes :)
This is how I stored my string:
std::string str = "504b0304140000000800b3ab584fd82c4d1ec01b00002a45000007000000"
"4348414e474553955bfb73db4872fed95775ffc364cf1593673e44ca92bd"
"aa3b27b6a4f5ea4eaf58f2de6ea5121c080c499cf03a0c2089fbd7a7bfee"
"...";
It goes for about 58 thousand lines, how could I select it?
|
I was able to select my huge variable by clicking at the beginning of my variable and Shift+click at the end of it. (@Ranoiaetep idea)
|
74,449,213
| 74,451,251
|
How to get all global variable addresses and size at runtime through llvm or clang
|
I'm analyzing c/c++ projects for memory errors tracking (out-of-bounds read/write). I would like to create at runtime a list of all global variables addresses , i.e. their boundaries.
Is there any workaround with LLVM (e.g. some llvm module pass) I can came up with, such that at runtime I'm able to locate all global variables and their corresponding size?
The desired outcomes is described in the following c pseudocode.
// Example of file.cc
int i;
int a[3] = {0, 1, 2};
char *s = "Simple string";
SOME_LIST_TYPE global_list;
void track_global_vars() {
for (GLOBAL_VAR gv: GLOBAL_VAR gvs) {
LIST_ITEM *li = (LIST_ITEM*) malloc(sizeof(LIST_ITEM));
li->start = gv.getAddress();
li->end = li->start + gv.getSize();
global_list.add(li);
}
}
int main(int argc, char *argv[]) {
track_global_vars();
// AT this point I would like to have:
// global_list -> [i_start, i_end] -> [a_start, a_end] -> [s_start, s_end] -> ...
// normal program execution
return 0;
}
Any suggestion or workarounds?
|
The LLVM pass AddressSanitizer already detects out of bounds memory accesses, including globals and also stack and heap. You can pass -fsanitizer=address to clang to use it. It's even been ported to GCC under the same flag. You can combine it with UBSan, the undefined behaviour sanitizer, as -fsanitize=address,undefined to catch even more errors, again available on both clang and gcc.
If for some reason you don't want ASan and you want to proceed with building a system that reflects on the sizes and addresses of global variables, you could declare a global in C extern SOME_LIST_TYPE global_list; and have an LLVM pass that fills in the data. Given a llvm::Module *M you can scan all global variables with for (auto GV : M->globals()) { (doxygen) and you can build a constant "GEP" which steps over one element of the global's type to get the pointer to the end. See the GEP faq. As a tip with LLVM's API, note that most of these instructions, Add, Mul, GEP, exist in two forms, subclasses of llvm::Instruction and subclasses of llvm::ConstantExpr. You need the second form if you want to make it constant data you can initialize your array with.
Use auto *the_array_to_fill = M->getNamedGlobal("global_list"); to get your global_list as an llvm::GlobalVariable, then call the_array_to_fill->setInitializer(...) to set its data. You'll need to prepare the data in the type and layout that you want it in, maybe an array with a struct of two members (begin and end) or an array of all begins then all ends, whatever works for you. The LLVM tutorial covers how to create LLVM IR which you'll need to do to build up the types and (Constant!) values you initialize your global with.
You may also want to the_array_to_fill->setLinkage(llvm::GlobalValue::AppendingLinkage); so that you get all the globals from all translation units combined into one array when linking, instead of a "multiple definition" error or using weak linkage and only getting one of them discarding the rest.
|
74,449,386
| 74,449,606
|
Can I use C++20 concepts for partial template specialization?
|
I was given an assignment on my computer science class to implement a String<T> class in C++ which would have print method throw an exception, unless T = char. So I defined a method for template<typename T> class String this way:
void print(std::basic_ostream<T> stream) {
throw StringTypeError("Can't print with these types");
}
And defined a specialization like so:
template<>
void String<char>::print(std::basic_ostream<char> stream) {
for(unsigned long i = 0; i < size; i++)
stream << charAt(i);
}
That totally works, however I've recently found out about concepts and decided to allow usage of print() for any type which can be <</>> into IO streams. I created a small concept:
template<typename T>
concept IO = requires(T a) {
std::cout << a;
std::cin >> a;
};
And tried to alter my specialization this way:
template<IO T>
void String<T>::print(std::basic_ostream<T> stream) {
for(unsigned long i = 0; i < size; i++)
stream << charAt(i);
}
But the compiler rejected with "Type constraint differs in template redeclaration" error.
Am I making a mistake which can be corrected or is it impossible to use concepts in this way? (if that's so, is there any concept-like alternatives?)
|
is there any concept-like alternatives?
There is an appropriate tool for the job, a particularly nice new feature with concepts and its related requires-clauses, one which is not possible with pre-C++20 SFINAE, namely that non-template member functions of class templates can be declared with requires-clauses. This means that you can define both of your mutually exclusive print member function in the primary template:
template<typename T>
class String {
void print(std::basic_ostream<T>&) requires (!IO<T>) {
throw StringTypeError("Can't print with these types");
}
void print(std::basic_ostream<T>& stream) requires (IO<T>) {
for(unsigned long i = 0; i < size; i++)
stream << charAt(i);
}
// ...
};
|
74,450,230
| 74,547,692
|
Context menu does not consistently work on arch linux?
|
I am using arch linux and a basic cpp xlib custom window manager. However, every time I right click to open the context menu it just flickers and disappears. I cannot use it at all. I also cannot use top drop down menus (file, edit, about, ect.) on any application. Is there anything in Xlib which I have to look out for to ensure I may use the context menus normally?
This is the case in every application I have tried. Only clue I have is in brave it occasionally displays the following message:
XGetWindowAttributes failed for window [WINDOW_ID]
The following simplified example also has this issue:
int main()
{
display = XOpenDisplay(nullptr);
root = DefaultRootWindow(display);
XSelectInput(display, root, SubstructureRedirectMask | SubstructureNotifyMask | StructureNotifyMask);
XGrabServer(display);
Window returned_root;
Window returned_parent;
Window* top_level_windows;
unsigned int num_top_level_windows;
XQueryTree(display, root, &returned_root, &returned_parent, &top_level_windows, &num_top_level_windows);
for(unsigned int i = 0; i < num_top_level_windows; ++i)
{
Frame(top_level_windows[i], true);
}
XFree(top_level_windows);
XUngrabServer(display);
for(;;)
{
XEvent event;
XNextEvent(display, &event);
switch (event.type)
{
case MapRequest:
{
Frame(event.xmaprequest.window, false);
XMapWindow(display, event.xmaprequest.window);
break;
}
case ButtonPress:
XRaiseWindow(display, event.xbutton.window);
break;
}
}
return true;
}
void Frame(Window window, bool created_before_manager)
{
//Retrieve attributes of window to frame
XWindowAttributes attr = {0};
XGetWindowAttributes(display, window, &attr);
//If window was created before window manager started, we should frame it only if it is visible and does not set override_redirect
if(created_before_manager && (attr.override_redirect || attr.map_state != IsViewable))
{
return;
}
//Create frame
Window frame = XCreateSimpleWindow(display, root, attr.x, attr.y, attr.width, attr.height, 5, 0xff0000, 0xffffff);
XReparentWindow(display, window, frame, 0, 0);
XMapWindow(display, frame);
XGrabButton(display, Button1Mask, Mod1Mask, window, None, ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None);
}
To be clear it also works with a super simple example such as:
int main()
{
Display* display = XOpenDisplay(nullptr);
for(;;) {}
return true;
}
The reason I believe the window manager is at fault is because this issue only occurs after I run the window manager.
I expected this to work out of the box. I have not found any information on context menus needing special treatment. They do have the override_redirect flag set to true, so I do not frame them. I cannot find information on any other special treatment required.
|
It is necessary to make sure the client window has input. I had the input set to whatever was clicked (frame, title bar, or client) because it worked fine as far as normal input is concerned. However, the context menus will only work if you make sure the input is set to the client window directly.
|
74,450,307
| 74,450,695
|
Is it necessary to have a co_return statement on each execution path of a coroutine that returns void
|
I wonder whether the below code is valid C++ code or if not using co_return results in undefined behavior.
IAsyncAction MyClass::MyCoroutine()
{
co_await someOtherClassInstance.SomeCoroutine();
}
I.e. is it necessary to adjust the code as follows?
IAsyncAction MyClass::MyCoroutine()
{
co_await someOtherClassInstance.SomeCoroutine();
co_return;
}
If the behavior is not undefined, what is the best practice (always add co_return or not) and what is the justification for doing so?
|
Omitting the co_return; statement is well defined here. According to [stmt.return.coroutine] this is allowed as long as p.return_void() is a valid expression (where p is the promise type).
C++/WinRT implements return_void() for IAsyncAction and IAsyncActionWithProgress (or rather the internal await adapter structs for those).
Since the co_return; statement is purely optional here, it is down to personal preference on whether to use it or not. Personally, I prefer reading code where the co_return; statement is present, for a few reasons:
It allows me to easily comment out part of the coroutine (e.g. for testing) without risking to turn it into a regular function.
I don't have to know the intricacies of the complex C++/WinRT library to figure out whether the code is correct.
The code stays correct if I ever decide to change its return type.
|
74,450,650
| 74,450,918
|
What's going on when we expand std::vector<>?
|
What happens when we do push_back with size() == capacity()?
I've heard a lot of opinions regarding this question. Most popular is: when the vector's size reaches its capacity, it allocates a new region of memory, copies the vector to the newly allocated memory, and inserts new value to the vector's end.
But, why do we have to do it? We have a virtual memory mechanism, we can just call realloc(vec.data(), (sizeof(vec::value_type) * vec.size()) * 2). The Allocator will give us a new memory page, and virtual addresses make the memory "consistent", so we don`t have to copy values from the vector.
Do I understand the virtual memory mechanism wrong?
|
You understand virtual memory mechanism correctly, basically you can create any amount of continuous page-aligned arrays in the proces' virtual memory space and they would be backed by non-contiguous physical memory.
But that is irrelevant to std::vector because std::allocator does not provide any API to take advantage of that, I think some see this as an oversight.
Just be mindful that C++ is not restricted to only architectures supporting virtual memory, although I think it would be an implementation detail of the standard library if it were implemented anyway.
No, you cannot use C realloc because C++ has objects with real lifetimes, everything is not just a blob of bytes that can be freely copied at whim, some special blobs might not like being moved and they will not appreciate it if you force them to.
Yes, if you are dealing with PODs, this would work with a custom::vector, not std::vector based on std::allocator.
There is a paper in works which addresses your concerns and goes beyond realloc, arguing "its day has passed" - P0901 which few days ago received rather positive feedback from the committee.
|
74,451,129
| 74,452,239
|
How do I perform a narrowing conversion from double to float safely?
|
I am getting some -Wnarrowing conversion errors when doubles are narrowed to floats. How can I do this in a well defined way? Preferably with an option in a template I can toggle to switch behavior from throwing exceptions, to clamping to the nearest value, or to simple truncation. I was looking at the gsl::narrow cast, but it seems that it just performs a static cast under the hood and a comparison follow up: Understanding gsl::narrow implementation. I would like something that is more robust, as according to What are all the common undefined behaviours that a C++ programmer should know about? static_cast<> is UB if the value is unpresentable in the target type. I also really liked this implementation, but it also relies on a static_cast<>: Can a static_cast<float> from double, assigned to double be optimized away? I do not want to use boost for this. Are there any other options? It's best if this works in c++03, but c++0x(experimental c++11) is also acceptable... or 11 if really needed...
Because someone asked, here's a simple toy example:
#include <iostream>
float doubleToFloat(double num) {
return static_cast<float>(num);
}
int main( int, char**){
double source = 1; // assume 1 could be any valid double value
try{
float dest = doubleToFloat(source);
std::cout << "Source: (" << source << ") Dest: (" << dest << ")" << std::endl;
}
catch( std::exception& e )
{
std::cout << "Got exception error: " << e.what() << std::endl;
}
}
My primary interest is in adding error handling and safety to doubleToFloat(...), with various custom exceptions if needed.
|
As long as your floating-point types can store infinities (which is extremely likely), there is no possible undefined behavior. You can test std::numeric_limits<float>::has_infinity if you really want to be sure.
Use static_cast to silence the warning, and if you want to check for an overflow, you can do something like this:
template <typename T>
bool isInfinity(T f) {
return f == std::numeric_limits<T>::infinity()
|| f == -std::numeric_limits<T>::infinity();
}
float doubleToFloat(double num) {
float result = static_cast<float>(num);
if (isInfinity(result) && !isInfinity(num)) {
// overflow happened
}
return result;
}
Any double value that doesn't overflow will be converted either exactly or to one of the two nearest float values (probably the nearest). You can explicitly set the rounding direction with std::fesetround.
|
74,451,237
| 74,451,394
|
Implicit conversion in concepts
|
Consider the following concept, which relies on the operator bool() conversion member function of std::is_lvalue_reference<T> and std::is_const<T>.
#include <type_traits>
template <typename T>
concept is_non_const_lvalue_reference =
std::is_lvalue_reference<T>{} && // Malformed for GCC 12.2 and MSVC 19.33
!std::is_const<std::remove_reference_t<T>>{};
static_assert(is_non_const_lvalue_reference<int&>);
static_assert(!is_non_const_lvalue_reference<int const&>);
static_assert(!is_non_const_lvalue_reference<int&&>);
See the test at https://compiler-explorer.com/z/G5ffeWfbx.
Both GCC and MSVC correctly report that the returned type of std::is_lvalue_reference<T>{} is not a Boolean value. But Clang 15 then applies the implicit conversion to bool and considers the concept definition above well-formed. In contrast, the !std::is_const<...>{} expression is considered a Boolean expression due to the ! operator.
The question: Is Clang 15 being too permissive in performing the implicit conversion to bool? Or is it a problem with GCC and MSVC? Perhaps it's unspecified in C++20?
P.S. Yes, I know I can replace the std::is_*<T>{} expressions with std::is_*_v<T>, and thus avoid the issue. But I'd like to understand when implicit conversions are expected/allowed to be performed.
|
The rule is, from [temp.constr.atomic]/3:
To determine if an atomic constraint is satisfied, the parameter mapping and template arguments are first substituted into its expression. If substitution results in an invalid type or expression, the constraint is not satisfied. Otherwise, the lvalue-to-rvalue conversion is performed if necessary, and E shall be a constant expression of type bool.
Here, std::is_lvalue_reference<T>{} is an atomic constraint - so it must have type bool. It doesn't.
|
74,451,764
| 74,452,066
|
Compile-time concatenation of std::initializer_list's
|
I would like to write some code like the following:
using int_list_t = std::initializer_list<int>;
struct ThreeDimensionalBox {
static constexpr int_list_t kDims = {1, 2, 3};
};
struct FourDimensionalBox {
static constexpr int_list_t kDims = {4, 5, 6, 7};
};
template<typename Box1, typename Box2>
struct CombinedBox {
static constexpr int_list_t kDims = Box1::kDims + Box2::kDims; // error
};
using SevenDimensionalBox = CombinedBox<ThreeDimensionalBox, FourDimensionalBox>;
Is there some way to fix the implementation of CombinedBox, so that SevenDimensionalBox::kDims is effectively bound to {1, 2, 3, 4, 5, 6, 7}?
I know that I can replace std::initializer_list<int> with a custom template class with a variadic int template parameter list, with concatenation effectively achieved via standard metaprogramming recursion techniques. I was just wondering if a solution exists using only std::initializer_list.
|
std::initializer_list can be initialized only as empty, with a list of brace-enclosed elements, or by copy.
However even with a copy construction, the lifetime of the actual array that std::initializer_list references is determined by the lifetime of the original std::initializer_list object that was initialized by a brace-enclosed element list. In other words copying the std::initializer_list does not copy the array or extend its lifetime.
Therefore it is impossible to concatenate std::initializer_lists. They are not meant to be used as a container. A std::initializer_list should mostly be used only as a function parameter as a lightweight way to pass a brace-enclosed list of elements of unspecified size to a function for it to then process the elements further.
You probably want std::array instead. Something like this (requiring C++17, but not C++20):
struct ThreeDimensionalBox {
static constexpr auto kDims = std::array{1, 2, 3};
};
struct FourDimensionalBox {
static constexpr auto kDims = std::array{4, 5, 6, 7};
};
template<typename T, std::size_t N, std::size_t M>
constexpr auto concat_arrays(const std::array<T, N>& a, const std::array<T, M>& b) {
// assumes `T` is default-constructible
std::array<T, N+M> r;
std::copy(std::begin(a), std::end(a), std::begin(r));
std::copy(std::begin(b), std::end(b), std::begin(r)+N);
return r;
}
template<typename Box1, typename Box2>
struct CombinedBox {
static constexpr auto kDims = concat_arrays(Box1::kDims, Box2::kDims);
};
using SevenDimensionalBox = CombinedBox<ThreeDimensionalBox, FourDimensionalBox>;
|
74,451,998
| 74,452,091
|
Why type deduction fails for a class member?
|
Let's assume that we have this small code:
template<typename T>
struct Test {
Test(T t) : m_t(t) {}
T m_t;
};
int main() {
Test t = 1;
}
This code easily compiles with [T=int] for Test class. Now if I write a code like this:
template<typename T>
struct Test {
Test(T t) : m_t(t) {}
T m_t;
};
struct S {
Test t = 1;
};
int main() {
S s;
}
This code fails to compile with the following error:
invalid use of template-name 'Test' without an argument list
I need to write it like Test<int> t = 1; as a class member to work. Any idea why this happens?
|
There is a difference between your two snippets - first Test t = 1 declares, defines, and initializes a new variable while the second only declares a member variable and specifies how it might be initialized.
The default member initializer is relevant only in the context of a constructor without t in its member initializer list and there can easily be multiple constructors, each initializing t in different way.
The following is valid C++, what should type of t be deduced to?
struct S {
Test t = 1;
S(){}
S(int):t(1){}
S(double):t(true){}
};
If this were to be supported, you hit the implementation issue of making type/size/layout of the class dependent on the definition of constructors which are likely in different translation units. Therefore it would make it impossible to define include classes such as S (if one moved the definitions to some .cpp) via header files.
|
74,452,464
| 74,460,122
|
CMake Error at CMakeLists.txt:14 (target_link_libraries)
|
I try to add GTest project to my solution. I have a project structure:
my project structure
I created Cryptograph and CryptographTests directories, after that created binTests and lib into CryptographTests.
I have a few CMakeLists.txt files:
Cryptograph/CMakeLists.txt:
cmake_minimum_required(VERSION 3.17)
project(Cryptograph)
set(CMAKE_CXX_STANDARD 17)
find_package(OpenSSL REQUIRED)
add_executable(Cryptograph main.cpp modulArithmetics.cpp modulArithmetics.h Speakers.cpp Speakers.h Crypt.cpp Crypt.h LongArithmetic.cpp LongArithmetic.h Signs.cpp Signs.h)
target_link_libraries(Cryptograph OpenSSL::SSL)
CryptographTests/CMakeLists.txt:
project(CryptographTest)
add_subdirectory(lib/googletest)
add_subdirectory(binTests)
CryptographTests/lib/CMakeLists.txt:
project(CryptographGTest)
add_subdirectory(lib)
CryptographTests/binTests/CMakeLists.txt:
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})
add_executable(runCommonTests FirstTest.cpp)
target_link_libraries(runCommonTests gtest gtest_main)
target_link_libraries(runCommonTests Cryptograph)
And CMakeLists.txt:
cmake_minimum_required(VERSION 3.17)
project(CryptographGlobal)
set(CMAKE_CXX_STANDARD 17)
set (SOURCE_FILES main.cpp)
add_executable(cryptograph_samples ${SOURCE_FILES})
include_directories(Cryptograph)
add_subdirectory(Cryptograph)
add_subdirectory(CryptographTests)
target_link_libraries(cryptograph_samples Cryptograph)
After that i got errors:
CMake Error at CryptographTests/binTests/CMakeLists.txt:6 (target_link_libraries):
Target "Cryptograph" of type EXECUTABLE may not be linked into another
target. One may link only to INTERFACE, OBJECT, STATIC or SHARED
libraries, or to executables with the ENABLE_EXPORTS property set.
CMake Error at CMakeLists.txt:14 (target_link_libraries):
Target "Cryptograph" of type EXECUTABLE may not be linked into another
target. One may link only to INTERFACE, OBJECT, STATIC or SHARED
libraries, or to executables with the ENABLE_EXPORTS property set.
Before this error i got error lool like can't connect to Cryptograph.lib, but after my changes errors also changed.
I try to add GTest project to my solution, but got a error
|
Your intuition that your test executable needs access to your Cryptograph code somehow in order to test it is correct. However, linking an executable to another executable is not possible.
You'll want to make Cryptograph a library instead so that it compiles once and your executables (cryptograph_samples and runCommonTests) can link to it.
The library should also not have a main(). Otherwise it would clash with your executable's main() at link-time. So assuming Cryptograph/main.cpp contains a main() function, it should be excluded.
So, replace this line:
add_executable(Cryptograph main.cpp modulArithmetics.cpp ...)
with:
add_library(Cryptograph STATIC modulArithmetics.cpp ...) # no main.cpp
Using a STATIC library is one approach. You could also use a SHARED or OBJECT library. See the first reference link below for more on CMake library targets in general.
And if you need to execute Cryptograph/main.cpp, you can turn it into its own executable that links to Cryptograph, like so in Cryptograph/CMakeLists.txt:
add_executable(CryptographApp main.cpp)
target_link_libraries(CryptographApp Cryptograph)
Resources
CMake target types and composition
GoogleTest guide on incorporating into an existing CMake project (~10 lines of code).
Integrating Google Test Into CMake Projects - by Matheus Gomes illustrates multiple methods of bringing dependencies (like googletest) into CMake projects in general.
|
74,453,091
| 74,453,203
|
C++ removing file with filesystem library doesn't work
|
I have a russian Roulette script written with C++. If two randomly generated numbers are the same, the script deletes a specified file.
People suggested to me that I should use C++17 for using the <filesystem> library in order to run file-related operations correctly. The removing operation runs if the conditions are matching. The if block runs correctly, but removing the file isn't happening.
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <filesystem>
//include filesystem and replace remove() with filesystem libs remove function
using namespace std;
namespace fs = std::filesystem;
int main(){
int minNumber = 1, maxNumber = 6;
int possibility,chamberNumber;
srand(time(0));
possibility = rand() % (maxNumber - minNumber + 1 ) + minNumber;
chamberNumber = rand() % (maxNumber - minNumber + 1 ) + minNumber;
cout << "First Number: " <<possibility<<endl<<"Second Number: " << chamberNumber<< endl;
if (possibility == chamberNumber){
std::filesystem::remove("C:\\Users\\mypath\\Desktop\\cppRoulette\\delete.txt");
cout << "You're Dead " <<possibility<< endl;
}
// else{
// cout << possibility << endl;
// }
return 0;
}
I use this line to compile my code:
g++ -std=c++17 rulet.cpp -o output
Here is a screenshot of the compiled output. Notice "delete.txt" still stands.
I am using WSL Debian, because I am using VS Code and native terminals don't work proper with g++. I may like smoothness of Linux a bit more, though.
I am looking for a proper and easier way to deal with files, just like in Python. I am attending a C++ crash course, so I am trying to learn it, switching to Python isn't on the table.
|
Your file path is wrong. I just got your code to work on my system by changing the path from E:\Test\delete.txt to /mnt/e/Test/delete.txt.
Under WSL, all Windows drives (C:, E:, etc.) are mounted under the /mnt directory, in subdirectories that match the drive letter (/mnt/c/, /mnt/e/, etc). In order to convert your Windows path for use in WSL, you need to do the following:
Replace all backslashes (\) with forward slashes (/).
Remove the colon (:) after the drive letter.
Convert the drive letter to lower case.
Prepend the string "/mnt/" to the path.
After this, your program works, and will delete the target file.
|
74,453,163
| 74,453,698
|
How to SecureZeroMemory on a string_view?
|
With this code:
std::string_view test = "kYp3s6v9y$B&E)H@";
SecureZeroMemory((void*)test.data(), test.length());
I get an exception:
Exception thrown: write access violation.
**vptr** was 0x7FF755084358.
With std::string i get no exception:
std::string test = "kYp3s6v9y$B&E)H@";
SecureZeroMemory((void*)test.data(), test.length());
What I'm doing wrong?
|
std::string_view is meant to be a read-only view into a string or memory buffer. In your particular example, the string_view is pointing at a read-only string literal, so no amount of casting will make it writable. But, if you do the following instead, then you can modify what a string_view points at, as long as it is being backed by a writable buffer:
char buffer[] = "kYp3s6v9y$B&E)H@";
std::string_view test = buffer;
SecureZeroMemory(const_cast<char*>(test.data()), test.length());
The std::string approach works (and BTW, the type-cast is not necessary) because the string makes a copy of the string literal data into its own internal writable memory buffer, which data() points at.
std::string test = "kYp3s6v9y$B&E)H@";
SecureZeroMemory(test.data(), test.length());
|
74,453,623
| 74,453,648
|
memcpy not behaving as expected
|
I have a char array with a fixed length of 2 and I want to read a 2 byte subsection of data from a buffer of size 1024 starting from index '0'.
char signature[2];
char arr[1024]; // this is populated with data
memcpy(&signature, &arr[0], sizeof this->signature);
If I manually look at the first two characters in arr with a for loop
for (int i = 0; i < 2; i++) {
std::cout << arr[i] << std::endl;
}
it outputs:
B
M
however when I read signature:
std::cout << signature << std::endl
std::cout << sizeof signature << std::endl;
it comes up with this:
BM�
3
I don't understand what's going on. My solution complies with all online examples of how to utilize memcpy.
build:
g++ -std=c++2a -I./include src/*.cpp -o res
I don't understand what's going on. My solution complies with all online examples of how to utilize memcpy.
|
The memcpy works but your code for displaying the result is incorrect.
Passing a char array to std::cout only works if the array contains a null-terminated string.
To display a char array that does not contain a null terminated string you could do something like:
for (char ch : signature)
std::cout << ch;
std::cout << '\n';
|
74,453,689
| 74,453,742
|
Class that automatically keeps track of the number of its instances in existence (C++)
|
I am tasked to have a class C which automatically keeps track of the number of its instances that exists, and to have a function that returns this number.
Here is what I have:
class C{
public:
static int num;
C(){++num;}
~C(){--num;}
int get_number_objs(){return num;}
};
int C::num = 0;
Does this do the trick?
This looks straightforward and might make sense, but I'm wondering if there are edge cases where you mess around with pointers or something like that where something falls through the cracks.
This is a solution verification more than anything else.
|
Does this do the trick?
Almost. You also need to increment num inside of the class's copy constructor, as well as the move constructor in C++11 and later.
Also, there is no point in having get_number_objs() if num is public, but since that does expose num to tampering from outside, num should be private instead. And get_number_objs() should be static.
Try this:
class C{
private:
static size_t num;
public:
C(){ ++num; }
C(const C&){ ++num; }
C(C&&){ ++num; }
~C(){ --num; }
static size_t get_number_objs(){ return num; }
};
size_t C::num = 0;
Alternatively, in C++17 and later, you can inline the num variable so you don't have to define it separately outside of the class:
class C{
private:
static inline size_t num = 0;
public:
C(){ ++num; }
C(const C&){ ++num; }
C(C&&){ ++num; }
~C(){ --num; }
static size_t get_number_objs(){ return num; }
};
|
74,453,958
| 74,454,045
|
Why do we need to make a local copy of smart_ptr first before passing it to other functions?
|
CppCon 2015: Herb Sutter "Writing Good C++14... By Default" Slide 50
Live on Coliru
I have seen the following guideline through above talk. However, I have hard time to understand the critical issues both solutions try to solve in the first place. All comments on the right side of the code are copied from original talk. Yes, I don't understand the comments on the slide either.
void f(int*);
void g(shared_ptr<int>&, int*);
shared_ptr<int> gsp = make_shared<int>();
int main()
{
// Issue 1>
f(gsp.get()); // ERROR, arg points to gsp', and gsp is modifiable by f
// Solution 1>
auto sp = gsp;
f(sp.get()); // ok. arg points to sp', and sp is not modifiable by f
// Issue 2>
g(sp, sp.get()); // ERROR, arg2 points to sp', and sp is modifiable by f
// Solution 2>
g(gsp, sp.get()); // ok, arg2 points to sp', and sp is not modifiable by f
}
Can someone please give me some advices what the problems are if we write code shown in Issue 1 and Issue 2 and why the solutions fix the problems?
|
f could be written like this:
void f(int* p)
{
gsp = nullptr;
*p = 5;
}
Since gsp is the only shared_ptr that owns the int, if it is cleared, then the pointer given to p is destroyed.
Basically, it is reasonable for functions which are given non-owning pointers (or references) to expect that the objects being pointed to are owned by someone outside of themselves, and that there is nothing they can do to cause them to be destroyed.
g is something similar, though with a reference as a parameter rather than a modifiable global:
void g(shared_ptr<int> &sp, int* p)
{
sp = nullptr;
*p = 5;
}
Both of these are warnings about making sure that, if some code passes an owned object to a function without explicitly transferring ownership, that function must ensure that there is nothing the called function can do to destroy that owned object by accident. In real-world scenarios, these will be fair more complex, as far as determining what has actually happened.
For cases of g, the parameter might be a reference to some complex object which happens to have the last shared_ptr to the int you also passed as a parameter. For f, the global object might be some "singleton" that manages a bunch of things, including ownership of objects, and this function just so happened to be passed a pointer to such an object. Inadvertently calling the wrong function from f or g can cause the pointer to become invalid.
|
74,454,057
| 74,454,058
|
How to do mask / conditional / branchless arithmetic operations in AVX2
|
I understand how to do general arithmetic operations in AVX2. However, there are conditional operations in scalar code I would like to translate to AVX2. How shall I do it?
For example, I would like to vectorize
double arr[4] = {1.0,2.0,3.0,4.0};
double condition = 3.0;
for (int i = 0; i < 4; i++) {
if (arr[i] < condition) {
arr[i] *= 1.75;
}
else {
arr[i] *= 6.5;
}
}
for (auto i : arr) {
std::cout << i << '\t';
}
Expected output:
1.75 3.5 19.5 26
How can I perform conditional operations like above in AVX2?
|
Use AVX2 conditional operations. Calculate both possible outputs on whole vectors. After that save those particular results that satisfy your conditions (mask). For your case:
double arr[4] = { 1.0,2.0,3.0,4.0 };
double condition = 3.0;
__m256d vArr = _mm256_loadu_pd(&arr[0]);
__m256d vMultiplier1 = _mm256_set1_pd(1.75);
__m256d vMultiplier2 = _mm256_set1_pd(6.5);
__m256d vFirstResult = _mm256_mul_pd(vArr, vMultiplier1); //if-branch
__m256d vSecondResult = _mm256_mul_pd(vArr, vMultiplier2); //else-branch
__m256d vCondition = _mm256_set1_pd(condition);
vCondition= _mm256_cmp_pd(vArr, vCondition, _CMP_LT_OQ); //a < b ordered (non-signalling)
// Use mask to choose between _firstResult and _secondResult for each element
vFirstResult = _mm256_blendv_pd(vSecondResult, vFirstResult, vCondition);
double res[4];
_mm256_storeu_pd(&res[0], vFirstResult);
for (auto i : res) {
std::cout << i << '\t';
}
Possible alternative approach instead of BLENDV is combination of AND, ANDNOT and OR. However BLENDV is much better both in simplicity and performance. Use BLENDV as long as you have as least SSE4.1 and don't have AVX512 yet.
For information about what _CMP_LT_OQ mean and can be see Dave Dopson's table. You can do whatever comparisons you want changing this accordingly.
There are detailed notes by Peter Cordes about conditional operations in AVX2 and AVX512. There are more examples on conditional vectorization (with SSE and AVX512 examples) in Agner Fog's "Optimizing C++" in chapter 12.4 on pages 121-124.
Maybe you aren't want to do some computations in else-branch or explicitly want to zero it. So that your expected output will look like
1.75 3.5 0.0 0.0
It that case you can you a bit more faster instruction sequence since you're not have to think about else-branch. There are at least 2 ways to achieve speedup:
Removing second multiplication, but keeping blendv. Instead of _secondResult just use zeroed vector (it can be global const).
Removing both second multiplication and blendv, and replacing blendv with AND mask. This variant uses zeroed vector as well.
Second way will be better. For example, according to uops table VBLENDVB on Skylake microarchitecture takes 2 uops, 2 clocks latency and can be done only once per clock. Meanwhile VANDPD have 1 uops, 1 clock latency and can be done 3 times in a single clock.
Worse way, just blending with zero
double arr[4] = { 1.0,2.0,3.0,4.0 };
double condition = 3.0;
__m256d vArr = _mm256_loadu_pd(&arr[0]);
__m256d vMultiplier1 = _mm256_set1_pd(1.75);
__m256d vFirstResult = _mm256_mul_pd(vArr, vMultiplier1); //if-branch
__m256d vZeroes = _mm256_setzero_pd();
__m256d vCondition = _mm256_set1_pd(condition);
vCondition = _mm256_cmp_pd(vArr, vCondition, _CMP_LT_OQ); //a < b ordered (non-signalling)
//Conditionally blenv _firstResult when IF statement satisfied, zeroes otherwise
vFirstResult = _mm256_blendv_pd(vZeroes, vFirstResult, vCondition);
double res[4];
_mm256_storeu_pd(&res[0], vFirstResult);
for (auto i : res) {
std::cout << i << '\t';
}
Better way, bitwise AND with a compare result is a cheaper way to conditionally zero.
double arr[4] = { 1.0,2.0,3.0,4.0 };
double condition = 3.0;
__m256d vArr = _mm256_loadu_pd(&arr[0]);
__m256d vMultiplier1 = _mm256_set1_pd(1.75);
__m256d vFirstResult = _mm256_mul_pd(vArr, vMultiplier1); //if-branch
__m256d vZeroes = _mm256_setzero_pd();
__m256d vCondition = _mm256_set1_pd(condition);
vCondition = _mm256_cmp_pd(vArr, vCondition, _CMP_LT_OQ); //a < b ordered (non-signalling)
// If result not satisfied condition, after bitwise AND it becomes zero
vFirstResult = _mm256_and_pd(vFirstResult, vCondition);
double res[4] = {0.0,0.0,0.0,0.0};
_mm256_storeu_pd(&res[0], vFirstResult);
for (auto i : res) {
std::cout << i << '\t';
This takes advantage of what a compare-result vector really is, and that the bit-pattern for IEEE 0.0 is all bits zeroed.
|
74,454,064
| 74,454,105
|
Variable types from inherited classes
|
If I have a class that inherits from a base class, can I use that base class as a variable type in c++?
class Component {
// Code here
};
class TransformComponent : public Component {
// Code here
};
class Entity {
// Code here
Component *getComponent(Component *searchComponent) {
// Code Here
}
};
as you can see here, I am using the base class "Component" as a return type and a variable type. The problem is that the user may input a "TransformComponent". The only reason I am asking this is because the "TransformComponent" class inherits from the "Component" class and there might be a way to do this?
<Entity>.getComponent(Component &TransformComponent());
The answer I'm looking for is one that works both for the return type, and the variable type.
|
Absolutely! It's one of the beauties of OOP. Your instanced class of type TransformComponent is both an instance of Component as well as TransformComponent.
If you had some function that returned a type of Component, this could return any class derived from Component as a Component! If you later wanted to refer to it as its sub-class, you might have to check its type and then cast to it, but what you want is absolutely possible, and you're going the right way about it.
In fact, in the example you describe, were you are using Component and the user might pass a TransformComponent, all of the base methods and properties that the Component possesses will be possessed by TransformComponent too. It will look and feel as if it was a Component, with all the benefits of being one.
The only time a problem will arise is if you specifically want to access the features of a TransformComponent, and the user passed a Component. The parent class doesn't know about the sub-class stuff, because it isn't an instance of one, it will throw up errors for you. Sub-classes build upon the base class, so they have all the base-class stuff, plus more. Basically its only an issue when your example is reversed.
|
74,454,998
| 74,455,429
|
Segmentation fault while trying to add an item at the end of a linked list
|
When I try to add an item at the end of a linked list it says segmentation fault (core dumped)
Here is the code
LinkedList :: LinkedList()
{
head = NULL;
}
void LinkedList :: InsertItem(int data)
{
Node *new_node;
new_node = new Node;
new_node -> data = data;
new_node -> next = NULL;
new_node -> next = head;
head = new_node;
cout<<"Node Added"<<"\n";
}
void LinkedList :: Display()
{
Node *curr;
curr = head;
while(curr != NULL)
{
cout<<curr->data<<"\t";
curr = curr -> next;
}
}
void LinkedList :: AddLast(int data)
{
Node *new_node = new Node;
new_node -> data = data;
new_node -> next = NULL;
Node *curr = head;
while (curr != NULL)
{
curr = curr -> next;
}
curr -> next = new_node;
}
When I run this, it says
Segmentation fault (core dumped)
I am trying to implement this linked list without a tail node. So how should I do it?
|
In the AddLast method, your iteration stops when curr == NULL. So when you attempt
curr -> next = new_node;
you get a segfault, since curr is null here.
To fix this, change your iteration to
while (curr->next != NULL)
That will ensure that the iteration stops at the last node, just like you need it to.
|
74,455,206
| 74,455,423
|
EPP Server SSL_Read hang after greeting
|
I have strange problems in ssl_read/ssl_write function with EPP server
After connected I read greeting message successfully.
bytes = SSL_read(ssl, buf, sizeof(buf)); // get reply & decrypt
buf[bytes] = 0;
ball+= bytes;
cc = getInt(buf);
printf("header: %x\n",cc);
printf("Received: \"%s\"\n",buf+4);
First 4 bytes are 00, 00, 09, EB and read 2539 bytes in greeting message.
After that, all operations like hello or logins are hand when SSL_read();
xml= "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><eppxmlns=\"urn:ietf:params:xml:ns:epp-1.0\"><hello/></epp>";
char bb[1000] = {0};
makeChar(strlen(xml)+4, bb);
memcpy(bb+4, xml, strlen(xml)+4);
bytes = SSL_write(ssl,xml,strlen(xml)+4);
usleep(500000); //sleep 0.5 sec
memset(buf, 0, 1024);
printf("read starting.\n");
bytes = SSL_read(ssl, buf, 1024); //always hang here
buf[bytes]=0;
printf("%d : %s", bytes, buf);
I am confused. I read RFC documentations but I can not find answer.
in EPP documentation, they said "In order to verify the identity of the secure server you will need the ‘Verisign Class 3 Public Primary Certification Authority’ root certificate available free from www.verisign.com".
is it important?
|
is it important?
Yes, as outlined in RFC 5734 "Extensible Provisioning Protocol (EPP) Transport over TCP", the whole security of an EPP exchange is bound to 3 properties:
access list based on IP address
TLS communication and verification of certificates (mutually, which is why you - as registrar aka client in EPP communication - have often to send in advance the certificate you will use ot the registry)
the EPP credentials used at <login> command.
Failure to properly secure the connection can mean:
you as registrar sending confidential information (your own EPP login, various details on domains you sponsor or not, including <authInfo> values, etc.) to a third party not being the registry
and in reverse, someone mimicking you in the eyes of the registry hence doing operations on which you will have to get the burden of, including financially for all domains bought, and legally.
But even in general for all cases of TLS handshake, if you want to be sure to be connected, as client, to the server you think you are, you need to verify its certificate.
Besides trivial things (dates, etc.), the certificate:
should at least be signed by an AC you trust (your choice who you trust)
and/or is a specific certificate with specific fingerprint/serial and other characteristics (but you will have to maintain that when the other party changes its certificate)
and/or matches DNS TLSA records
In short, if you are new to both EPP and TLS and C/C++ (as you state yourself in your other question about Verisign certificate), I hugely recommend you do not try to do all of this by yourself at a so low level (for example you should never manipulate XML as you do above, it shouldn't be a string. Again, there are libraries to properly parse and generate XML documents). You should use an EPP library that leverage most of the things for you. Your registry may provide an "SDK" that you can use, you should ask it.
PS: your read is probably hanging because you are not sending the payload in the correct fashion (again, something an EPP library will do for you). You need to send the length, as 4 bytes (which you need to compute after converting your string to bytes using the UTF-8 encoding), and then the payload itself. I am not sure this is what your code does. Also your reading part is wrong: you should first read 4 bytes from server, this will give you the length (but do note they can theoretically arrive not necessarily in a single packet so one "ssl read" might not give all 4 of them, you need a loop), after which you know the length of the payload you will get which allows you to set up proper buffers, if needed, as well as detecting properly when you received everything.
|
74,455,397
| 74,455,491
|
Why doesn't this class forward declaration compile in C++?
|
I'm sure that this has been asked, but I cannot find the question or answer, so here is the minimal code I tried to compile.
// goof4.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
class A;
class B
{
public:
A func() { return A{}; }
};
class A
{
};
int main()
{
B b;
auto a = b.func();
}
The declaration of B::func gives a "use of undefined type 'A' Error C2027 in MSVC 2022 using /std:c++20. I would have thought that the forward declaration of "class A" would have allowed the compiler to work on B::func until such time as class A was defined. Any help?
|
Because you have the function body using the (at that point) undefined type A in the class B itself and in a function body the type must already be defined.
just do A funct(); in the class B itself
and put the function body and after defining A,
A B::funct() { return A{}; }
https://ide.geeksforgeeks.org/2db37ea7-a62c-487b-8af5-10af8cebc3c6
|
74,455,518
| 74,455,594
|
Return type of function-template not const T&?
|
In the example below the type of the instantiation f<int&>(a) is reported to be int&.
template<typename T>
const T& f(const T& x) {
return x;
}
int main() {
int a{0};
decltype(f<int&>(a))::_;
}
But why is the type not const int& ?.
Edit:
The question is also why f<int&>(0) gives x as int& and not as const int&?
|
References themselves cannot be const-qualified (only the type they reference can), so const is ignored in const T if T is a reference type.
References-to-references also don't exist. The reference collapsing rules say that trying to form a lvalue references to lvalue reference to type U will form a lvalue reference to type U.
So in the end, if T is a lvalue reference type, const T& is the same type as T, in your case int&.
There isn't really a point to having the template argument be a reference and having the return value be a reference to the template parameter. You probably just want f<int>(a) instead of f<int&>(a). (Although you haven't said why you are interested in the behavior of f<int&>.)
|
74,455,536
| 74,460,538
|
What is the motivation of a separate config.hpp in boost spirit X3 program structure?
|
The title itself should be quite clear, but for more context, I was going through the tutorial about x3 program structure in order to re-structure my own baby-parsing-project before adding a recursive AST, and it is not clear to me what level of complexity management I can achieve using the proposed layers.
Particularly, I am confused at what the config.hpp enables. I could find at least one person had similar interrogations.
The content of this file is:
/*=============================================================================
Copyright (c) 2001-2018 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_X3_MINIMAL_CONFIG_HPP)
#define BOOST_SPIRIT_X3_MINIMAL_CONFIG_HPP
#include <boost/spirit/home/x3.hpp>
namespace client { namespace parser
{
namespace x3 = boost::spirit::x3;
using iterator_type = std::string::const_iterator;
using context_type = x3::phrase_parse_context<x3::ascii::space_type>::type;
}}
#endif
The motivations as stated in the documentation are: Here, we declare some types for instatntaiting our X3 parser with. Rememeber that Spirit parsers can work with any ForwardIterator. We'll also need to provide the initial context type. This is the context that X3 will use to initiate a parse. For calling phrase_parse, you will need the phrase_parse_context like we do below, passing in the skipper type.
My guess is this module is useful in complex project, but does not bring much for my simplistic application: am I wrong?
On a larger scope and for future reference, what would be is a good rule of thumb/redline not to cross in terms of modularity in the context of x3 parsers? (my lack of experience here is striking!)
|
Again, you're asking the big, core questions!
You don't need a config.hpp.
However, if you spread definition of rules across translation units, you will need to decide on the concrete template instantiations you need to be part of your object files.
The two variable parameters here are
iterator type
context type
The X3 examples all assume you will have a single set for your entire grammar. The developers have decided that it would be a good way to emphasize this by putting these "global parameters" in a central header.
There are many documented cases on this site where people have run into linker errors when working from one of the spirit examples, when they switched iterator types (e.g. from std::string::iterator to std::string::const_iterator) or by introducing another skipper.
Keep in mind you might want to facilitate multiple iterator/context combinations. Nothing prevents you from instantiating parse_rule functions for different combinations of parameters: BOOST_SPIRIT_INSTANTIATE.
Finally:
Q. My guess is this module is useful in complex project, but does not bring much for my simplistic application: am I wrong?
You are correct. In fact, I think that X3 shines when you can encapsulate the entire grammar inside a translation unit so that you don't need to deal with explicit instantiations, or even BOOST_SPIRIT_DEFINE - except for recursive rules.
|
74,455,595
| 74,457,146
|
regex_token_iterator<> sometimes misses matched substrings
|
I used regex_token_iterator<> to get all matched substrings in a line, as suggested in this question.
But the code sometimes misses 2nd matched substrings in lines, and the lines where this miss happens changes at different runs.
Is this a bug of regex_token_iterator<>, or is there something wrong in my code?
The compiler I used is Apple clang version 14.0.0 (clang-1400.0.29.202), and I used -std=c++14 to compile the following code.
I also tried another suggestion in the question above, which is to use while-loop to repeatedly apply regex_search(), and that version of code worked properly. I just want to know why the version with regex_token_iterator<> is not working, whether my usage is wrong or not.
code:
#include<regex>
#include<iostream>
#include<string>
#include<fstream>
#include<sstream>
using namespace std;
struct bad_from_string : bad_cast{
const char* what() const noexcept override{
return "bad cast from string";
}
};
template<typename T>
T from_string(const string& s){
istringstream is{s};
T t;
if(!(is>>t))
throw bad_from_string{};
return t;
}
int main(){
regex pat{R"((\d{1,2})/(\d{1,2})/(\d{4}))"}; // e.g. 7/21/2022
ifstream ifs{"test_regex_token_iterator.txt"};
ofstream ofs{"test_out_regex_token_iterator.txt"};
regex_token_iterator<string::iterator> rend; // default constructor is used for indicating the end of the sequence
for(string line; getline(ifs, line);){
smatch matches;
string replace_pattern;
int month{0}, day{0}, year{0};
regex_token_iterator<string::iterator> riter(line.begin(), line.end(), pat);
// for each matched substring, replace it individually
while(riter!=rend){
string matched_substring{(*riter).str()};
// *riter returns a reference to the sub_match object riter is pointing to.
// sub_match is not a string. sub_match::str() returns the string of the sub_match.
// put each matched substring into variable "matches"
regex_search(matched_substring, matches, pat);
// get the day, month, and year values in int
day = from_string<int>(matches.str(2));
month = from_string<int>(matches.str(1));
year = from_string<int>(matches.str(3));
// here make replace_pattern yyyy-mm-dd
if(month<10 && day<10)
replace_pattern = to_string(year)+"-0"+to_string(month)+"-0"+to_string(day); // both day and month need the fron '0'
else if(month<10)
replace_pattern = to_string(year)+"-0"+to_string(month)+"-"+to_string(day);
else if(day<10)
replace_pattern = to_string(year)+"-"+to_string(month)+"-0"+to_string(day);
else
replace_pattern = to_string(year)+"-"+to_string(month)+"-"+to_string(day);
line = regex_replace(line, regex(matched_substring), replace_pattern); // regex_replace() returns a string
// since I want to replace only 1 matched substring *riter, I use the exact substring
// in the place of regex pattern
++riter; // move to the next matched substring
}
ofs << line << endl;
}
return 0;
}
test_regex_token_iterator.txt:
12/01/2022 - 12/31/2022
12/01/2022 - 12/31/2022
12/01/2022 - 12/31/2022
12/01/2022 - 12/31/2022
10/01/2022 - 10/31/2022
10/01/2022 - 10/31/2022
10/01/2022 - 10/31/2022
10/01/2022 - 10/31/2022
10/01/2022 - 10/31/2022
sample test_out_regex_token_iterator.txt (but the result changes in different runs):
2022-12-01 - 12/31/2022
2022-12-01 - 2022-12-31
2022-12-01 - 12/31/2022
2022-12-01 - 12/31/2022
2022-10-01 - 10/31/2022
2022-10-01 - 2022-10-31
2022-10-01 - 10/31/2022
2022-10-01 - 10/31/2022
2022-10-01 - 10/31/2022
I expected all the matched substrings, including the dates in the 2nd column, were replaced, but only part of them were replaced properly.
The expected result:
2022-12-01 - 2022-12-31
2022-12-01 - 2022-12-31
2022-12-01 - 2022-12-31
2022-12-01 - 2022-12-31
2022-10-01 - 2022-10-31
2022-10-01 - 2022-10-31
2022-10-01 - 2022-10-31
2022-10-01 - 2022-10-31
2022-10-01 - 2022-10-31
|
enabling address sanitiser shows that your code is causing undefined behaviour: https://godbolt.org/z/n3rnn9nqY
riter contains iterators from line but at the end of your while loop you reassign line, invalidating line's iterators and therefore invalidating riter, when you then try to increment riter you enter the realms of undefined behaviour.
Adding a separate string for your output fixes the problem: https://godbolt.org/z/Grqe1vv5x
for(string line; getline(ifs, line);){
smatch matches;
string outputLine = line;
string replace_pattern;
int month{0}, day{0}, year{0};
regex_token_iterator<string::iterator> riter(line.begin(), line.end(), pat);
// for each matched substring, replace it individually
while(riter!=rend){
string matched_substring{(*riter).str()};
// *riter returns a reference to the sub_match object riter is pointing to.
// sub_match is not a string. sub_match::str() returns the string of the sub_match.
// put each matched substring into variable "matches"
regex_search(matched_substring, matches, pat);
// get the day, month, and year values in int
day = from_string<int>(matches.str(2));
month = from_string<int>(matches.str(1));
year = from_string<int>(matches.str(3));
// here make replace_pattern yyyy-mm-dd
if(month<10 && day<10)
replace_pattern = to_string(year)+"-0"+to_string(month)+"-0"+to_string(day); // both day and month need the fron '0'
else if(month<10)
replace_pattern = to_string(year)+"-0"+to_string(month)+"-"+to_string(day);
else if(day<10)
replace_pattern = to_string(year)+"-"+to_string(month)+"-0"+to_string(day);
else
replace_pattern = to_string(year)+"-"+to_string(month)+"-"+to_string(day);
outputLine = regex_replace(outputLine, regex(matched_substring), replace_pattern); // regex_replace() returns a string
// since I want to replace only 1 matched substring *riter, I use the exact substring
// in the place of regex pattern
++riter; // move to the next matched substring
}
ofs << outputLine << endl;
}
|
74,456,525
| 74,456,719
|
How to define 'i' in a (I think) constant array and the sum in c++ with variables?
|
I keep on getting an error message about line 29, and that the 'i' in "individualCommission[i]" isn't defined. Also, I am trying to find the sum of the entire array.
#include <iostream>
#include <iomanip>
using namespace std;
void heading( string assighnmentName ); // prototype - declare the function
void dividerLine( int length, char symbol );
int main()
{
// assighnment heading
heading( "GPA Calculator" );
//create variables to hold user data and calculated data
double commissionRate = 0.00;
int salesNumber = 0;
cout << endl;
cout << "Hello there! How many sales did you make? ";
cin >> salesNumber;
if( salesNumber <= 0 )
{
cout << "Invalid entry - enter 1 or more, please" << endl;
}
// convert the salesNumber into a constant to use with our array structures & create array structures
const int arraySize = salesNumber;
string salesName[ arraySize ];
double salesAmount[ arraySize ];
double individualCommission[ arraySize ];
// collect input from user for arraySize
for ( int i = 0; i < arraySize; i++ )
{
cin.ignore( 256, '\n' ); // because it doesn't like the switches with cin to string
cout << "What is your #" << i + 1 << " sale labeled? ";
getline( cin, salesName[i] );
do
{
cout << "How much does " << salesName[i] << " cost? $ ";
cin >> salesAmount[i]; //pointing the location in the array
if( salesAmount[i] <= 0 )
{
// add this line to prevent keyboard buffer issues //
cout << "Invalid entry - input valure more than zero";
}
// the else if statments
if( salesAmount[i] <= 10000 )
{
commissionRate = .1;
}
else if( salesAmount[i] <= 15000 )
{
commissionRate = .15;
}
else if( salesAmount[i] > 15,000 )
{
commissionRate = .2;
}
}while( salesAmount[i] <= 0 );
}
individualCommission[i] = salesAmount[i] * commissionRate)[i];
dividerLine( 40, '-' );
for( int i = 0; i < arraySize; i++ )
{
cout << salesName[i];
cout << "\t\t\t";
cout << salesAmount[i];
cout << "\t\t\t";
cout << individualCommission[i];
cout << endl;
}
// This is what I need: comissionEarned = BLAH BLAH SOMETHING I DONT KNOW THE ANSWER TO
// cout << "Total Commission: " << setw(10) << setprecision(2) << fixed << "$ " << commissionEarned << endl;
dividerLine( 40, '-' );
cout << endl << "Thank you for using my commission calculator!";
return 0;
}
// DOMAIN OF MY FUNCTIONS //////////////////////////////////////////////////
void heading( string assighnmentName )
{
cout << endl << "Amelia Schmidt" << endl;
cout << "Mrs. Carr, Period 3" << endl;
cout << assighnmentName << endl;
cout << "November 8, 2022" << endl << endl;
dividerLine( 40, '-' );
}
void dividerLine( int length, char symbol )
{
for( int i = 0; i < length; i++ )
{
cout << symbol;
}
cout << endl;
} // end the function dividerLine(int, char)
This is the error message I keep getting.
I've tried some arr statements, but I honestly don't know what they actually do or if I'm writing the wrong statement. I have no clue how to work with the [i] undefined part.
|
Your code was simple to fix. You had put a statement outside the for and it couldn't save the data inside the array. The change was made in line 61:
#include <iostream>
#include <iomanip>
#include <numeric>
using namespace std;
void heading( string assighnmentName ); // prototype - declare the function
void dividerLine( int length, char symbol );
int main() {
// assighnment heading
heading( "GPA Calculator" );
//create variables to hold user data and calculated data
double commissionRate = 0.00;
int salesNumber = 0;
cout << endl;
cout << "Hello there! How many sales did you make? ";
cin >> salesNumber;
if( salesNumber <= 0 ) {
cout << "Invalid entry - enter 1 or more, please" << endl;
}
// convert the salesNumber into a constant to use with our array structures & create array structures
const int arraySize = salesNumber;
string salesName[ arraySize ];
double salesAmount[ arraySize ];
double individualCommission[ arraySize ];
// collect input from user for arraySize
for ( int i = 0; i < arraySize; i++ ) {
cin.ignore( 256, '\n' ); // because it doesn't like the switches with cin to string
cout << "What is your #" << i + 1 << " sale labeled? ";
getline( cin, salesName[i] );
do {
cout << "How much does " << salesName[i] << " cost? $ ";
cin >> salesAmount[i]; //pointing the location in the array
if( salesAmount[i] <= 0 ) {
// add this line to prevent keyboard buffer issues //
cout << "Invalid entry - input valure more than zero";
}
// the else if statments
if( salesAmount[i] <= 10000 ) {
commissionRate = .1;
}
else if( salesAmount[i] <= 15000 ) {
commissionRate = .15;
}
else if( salesAmount[i] > 15,000 ) {
commissionRate = .2;
}
} while( salesAmount[i] <= 0 );
individualCommission[i] = salesAmount[i] * commissionRate;
}
dividerLine( 40, '-' );
for( int i = 0; i < arraySize; i++ ) {
cout << salesName[i];
cout << "\t\t\t";
cout << salesAmount[i];
cout << "\t\t\t";
cout << individualCommission[i];
cout << endl;
}
double comissionEarned = accumulate(individualCommission, individualCommission+arraySize, 0);
cout << "Total Commission: " << setw(10) << setprecision(2) << fixed << "$ " << comissionEarned << endl;
dividerLine( 40, '-' );
cout << endl << "Thank you for using my commission calculator!";
return 0;
}
// DOMAIN OF MY FUNCTIONS //////////////////////////////////////////////////
void heading( string assighnmentName ) {
cout << endl << "Amelia Schmidt" << endl;
cout << "Mrs. Carr, Period 3" << endl;
cout << assighnmentName << endl;
cout << "November 8, 2022" << endl << endl;
dividerLine( 40, '-' );
}
void dividerLine( int length, char symbol ) {
for( int i = 0; i < length; i++ ) {
cout << symbol;
}
cout << endl;
} // end the function dividerLine(int, char)
However I would recommend giving you a couple of tips about the code.
First, always try to understand where the problem lies and don't post hundreds of badly formatted lines of code. Even just a minimum of reproducible code is enough. This also allows us to focus more on the error without thinking about what your program is really doing.
Also, in the current C++ standard, automatic array allocation is only allowed via compile-time constants. So if you want to create an array with a user-entered size, you just have to use dynamic allocation -> pointers.
That said, I hope I was clear.
|
74,457,085
| 74,457,300
|
[[nodiscard]] attribute different compilation result for GCC and Clang
|
#include <iostream>
#include <memory>
class A
{
public:
static [[nodiscard]] std::unique_ptr<A> create();
virtual int get_version() = 0;
virtual ~A() = default;
};
class B : public A
{
public:
[[nodiscard]] int get_version() override
{
return 20;
}
};
std::unique_ptr<A>
A::create()
{
return std::make_unique<B>();
}
int main()
{
auto a = A::create();
[[maybe_unused]] int v = a->get_version();
}
I tried to use [[nodiscard]] to not allow ignoring the return value of A::create().
But, I get different compilation output in GCC and Clang.
Tried with
GCC: 8.5
Clang: 15.0.0
Compilation options: -O3 -std=c++17
Godbolt link: https://godbolt.org/z/qa7TfcK9f
GCC:
<source>:7:12: warning: attribute ignored [-Wattributes]
static [[nodiscard]] std::unique_ptr<A> create();
^
<source>:7:12: note: an attribute that appertains to a type-specifier is ignored
ASM generation compiler returned: 0
<source>:7:12: warning: attribute ignored [-Wattributes]
static [[nodiscard]] std::unique_ptr<A> create();
^
<source>:7:12: note: an attribute that appertains to a type-specifier is ignored
Execution build compiler returned: 0
Program returned: 0
Clang:
<source>:7:14: error: 'nodiscard' attribute cannot be applied to types
static [[nodiscard]] std::unique_ptr<A> create();
^
1 error generated.
ASM generation compiler returned: 1
<source>:7:14: error: 'nodiscard' attribute cannot be applied to types
static [[nodiscard]] std::unique_ptr<A> create();
^
1 error generated.
Execution build compiler returned: 1
Am I doing something wrong? And why does these compilers have different behavior?
This code works with MSVC v19.33 properly without any errors or warnings: https://godbolt.org/z/dWsv4jTo5
|
You can see here https://eel.is/c++draft/class.mem#general that the attribute can only appear first in a member declaration. Hence this
static [[nodiscard]] std::unique_ptr<A> create();
is wrong. And should be
[[nodiscard]] static std::unique_ptr<A> create();
Your code has a typo.
Newever versions of gcc report a more clear error:
source>:7:12: error: standard attributes in middle of decl-specifiers
7 | static [[nodiscard]] std::unique_ptr<A> create();
| ^
<source>:7:12: note: standard attributes must precede the decl-specifiers to apply to the declaration, or follow them to apply to the type
<source>:7:12: warning: attribute ignored [-Wattributes]
<source>:7:12: note: an attribute that appertains to a type-specifier is ignored
Actually I do not know if it has to be reported as error or if a warning is ok too. I don't think it relly matters, because you need to fix it anyhow, and unless you ignore warnings you cannot miss it. MSCV not diagnosing the issue is not nice. However, you should also keep in mind that [[nodiscard]] like similar attributes merely encourage the compiler to issue a warning. There is no gurantee to get a warning when it is discarded.
|
74,457,351
| 74,457,563
|
Can a parent class which is reinterpreted as a child class use the child's functions in its functions?
|
I want to call the child's function from parent's function in reinterpreted class, like below.
Example
#include <iostream>
class A {
public:
void func1() {
// some code
func2();
// some code
}
protected:
virtual void func2() {
printf("class A\n");
}
};
class B : public A {
protected:
virtual void func2() {
printf("class B\n");
}
};
int main() {
A* ab = new A();
ab->func1(); // this print "class A"
B* bab = reinterpret_cast<B*>(ab);
bab->func1(); // this also print "class A"
// I want to print "class B" when I use bab->func1()
}
In this situation, Is there any way to print class B using the reinterpreted class bab without redefining func1?
|
For C++ polymorphism to kick in, you must create an instance of the derived class somewhere, but you can store a pointer to the base class. Using the base-class pointer will dispatch to the overridden functions of the derived class. So your definition of A and B is fine, your usage in the main function is not. reinterpret_cast is not intended for this.
#include <iostream>
#include <memory>
class A {
public:
void func1() {
// some code
func2();
// some code
}
protected:
virtual void func2() {
printf("class A\n");
}
};
class B : public A {
protected:
virtual void func2() {
printf("class B\n");
}
};
int main() {
{
// This works, but don't do this. Naked "new" is not modern C++ and dangerous.
A* ab = new B();
ab->func1();
delete ab;
}
{
// VARIANT 2: use smart pointers
std::unique_ptr<A> ab = std::make_unique<B>();
ab->func1();
}
{
// VARIANT 3: A non-smart pointer is okay, as long as it
// 1. references an existing allocated object
// 2. the pointer does not outlive the object it points to
B b;
A* ab = &b;
ab->func1();
}
{
// VARIANT 4: Like Variant 3, but with reference instead of pointer
B b;
A& ab = b;
ab.func1();
}
}
Output
class B
class B
class B
class B
https://godbolt.org/z/8e5E85nx5
EDIT: Try to avoid allocation with new. Any memory allocated in this fashion must be freed by you using delete and it is very easy to forget (I did when I first wrote this answer, kinda proving my point). Even if you do delete the memory at the end of your function, there is the possibility that your code never reaches this statement, e.g. if exceptions are thrown somewhere between new and delete.Here is some further reading:
Why is it a bad idea to use 'new'?
Why should C++ programmers minimize use of 'new'?
|
74,457,605
| 74,458,654
|
Why can't wcout use the hex keyword to output hexadecimal format?
|
I have entered a wchar type variable and want to see the hexadecimal of the variable. However,when I use the wcout keyword, I can't always output hexadecimal. Is there a grammatical error?
#include <iostream>
void test_wide_character_input() {
using namespace std;
wchar_t ch = L'?';
wcout << ch << endl;
wcout << hex;
wcout << ch << endl;
cout << "---" << endl;
wchar_t w_ch = L'1';
wcout << w_ch << endl;
cout << w_ch << endl;
cout << hex;
cout << w_ch << endl;
}
int main() {
test_wide_character_input();
return 0;
}
out:
PS C:\Users\j30022312\Downloads\Relearn_C_Plus_Plus-main\Relearn_C_Plus_Plus-main\PART_2_The_C++_Library\Chapter_8_The_IO_Library\examples> .\a.exe
?
?
---
1
49
31
|
Change the character to unsigned int type before converting it to hexadecimal like this:
wcout << hex << (unsigned)ch;
|
74,457,857
| 74,463,594
|
ReadFile buffer output is weird (prints content + some more)
|
I am trying to open a file and read its content using the Win32 API:
HANDLE hFileRead = CreateFileA(FilePath,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
LARGE_INTEGER fileSize = { 0 };
DWORD cbFileSize = GetFileSizeEx(hFileRead, &fileSize);
PBYTE buffer = (PBYTE)HeapAlloc(GetProcessHeap(), 0, fileSize.QuadPart);
DWORD dwBytesRead = 0;
NTSTATUS s = ReadFile(hFileRead,
buffer,
fileSize.QuadPart,
&dwBytesRead,
NULL);
std::cout << buffer << "\n"; // <<< expect to print "asdasd" but prints "asdasd"+random chars (1 or more each run)
What I want to get is the file content (.txt in this case).
What I get is the content of a .txt file + some more random chars (its different for each run).
I tried to write the buffer indexed, it seems that the buffer prints more than its size (?)
What am I doing wrong?
|
std::cout << buffer expects buffer to be null-terminated, but it is not. You need to allocate space for the terminator, eg:
PBYTE buffer = (PBYTE)HeapAlloc(GetProcessHeap(), 0, fileSize.QuadPart + 1);
...
buffer[dwBytesRead] = 0;
Alternatively, you can use cout.write() instead, then you don't need a terminator, eg:
std::cout.write(buffer,dwBytesRead);
|
74,458,909
| 74,459,476
|
How to make the QGraphicsView size consistent with the size of the image and the main window in Qt?
|
I'm developing a graphic editor with Qt. I'm using a QGraphicsView to display the picture and need to resize it so that it's consistent with the size of the image and the main window.
Now I'm resizing it like this (in the method of the MainWindow class):
ui->graphicsView->resize(picture->width, picture->height); // ui here is Ui::MainWindow* pointer
I call this method when I open the image. It looks normal for small pictures, but when I open a big one, its size becomes more than the size of the window and I can't scroll it. I can set the size of the graphicsView to the maximum of the picture and the main window sizes, but this doesn't solve the problem, because when I make the main window smaller, the picture will keep its size and will be larger than the window. So, I think I need to resize the image when resizing the main window.
I know there is the system of signals and slots in Qt, but I can't find the suitable slot of QMainWindow. So, my question is: how to catch the changing of the size of the main window to resize the graphicsView?
|
just override resizeEvent() in QMainWindow
const QSize &QResizeEvent::size() const
Returns the new size of the widget.
void MyMainWindow::resizeEvent(QResizeEvent* event)
{
// ui->graphicsView->resize(event->size());
QMainWindow::resizeEvent(event);
}
|
74,459,462
| 74,460,041
|
Why C++ does not perform RVO to std::optional?
|
I am wondering why C++ does not perform RVO to std::optional<T> when returning T.
I.e.,
struct Bar {};
std::optional<Bar> get_bar()
{
return Bar{}; // move ctor of Bar called here
// instead of performing RVO
}
Bar get_bar2()
{
return Bar{}; // NO move ctor called
// RVO performed
}
std::optional<Bar> get_bar_rvo()
{
std::optional<Bar> opt;
opt.emplace();
return opt; // NO move ctor called
// ROV performed
}
In this above case, get_bar2 performs RVO while get_bar does not.
With a little bit more hint, the compiler is able to optimize get_bar_rvo, but the code get longer and annoying.
From the reference, I understand that get_bar does not meet the requirement of "Mandatory elision of copy/move operations"
In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:
Since std::optional<T> and T are not the same class type, so RVO is not mandatory.
However, I think that performing RVO to std::optional<T> should be very easy and would be very useful, without the need to manually write the longer code as get_bar_rvo.
Why my compile fails to recognize and optimize the get_bar just like get_bar2?
Environments: MacOS
Apple clang version 13.1.6 (clang-1316.0.21.2.5)
Target: arm64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Compiled with -std=c++17 -O3
|
get_bar_rvo does not perform RVO, it performs NRVO (Named Return Value Optimization). This is not guaranteed.
For get_bar, instead of constructing a Bar yourself, you can leave that to std::optional using std::make_optional or its in-place constructor (6):
std::optional<Bar> get_bar()
{
return std::make_optional<Bar>();
// or return std::optional<Bar>(std::in_place);
}
This performs RVO as expected.
|
74,459,498
| 74,459,898
|
C++ how to write a wrapper for a C api that doesn't know about class instances?
|
In a project that we intended to write in C++, we use a C-library. This C library provides functions to register callbacks, that are called on each interrupt. We register our callbacks inside the constructor.
So we basically have the following (simplified) structure:
OurClass::OurClass() {
//the registerISRCallback is the C function, that accepts as first parameter the pin,
//the interrupt is expected on and as second parameter a function pointer:
//void (*callbackFunction)(int number, int time)
registerISRCallback(SCLK, handle_interrupt);
}
void OurClass::handle_interrupt(int pin, int time) {
//example: Blink a Led on the instance-LedPin
}
the problem however is twofold:
because it is a member function, the handle_interrupt method has the signature void (OurClass::*)(int, int). Therefore it is not possible to use it like this.
this class can be instantiated multiple times, so using a singleton would also not work, because our callback may differ per instance (each instance could for example have a different LedPin.
are there any more solutions to use this C API function inside our class and keep the code clean and readable?
|
Your class may integrate a static method that you pass as a C callback function (provided the calling conventions are made compatible; if not possible, wrap it in a pure C call).
In addition, let your class keep a static table of the created instances, in correspondence to the pins. When a callback is invoked, by knowing the pin, you will know which instance to activate.
|
74,459,707
| 74,459,855
|
Why do the C++ Core Guidelines not recommend to use std::optional over pointers when approriate?
|
In the C++ Core Guidelines std::optional is only referred once:
If you need the notion of an optional value, use a pointer, std::optional, or a special value used to denote “no value.”
Other than that, it is not mentioned in the guidelines, so in particular there is no recommendation to use it instead of a pointer, when expressing the intent of an optional value.
Are there any disadvantages of the usage of std::optional in comparison to a pointer that might be null in a non-polymorphic context?
So std::optional is only referred as a side note and as the second option to a pointer.
To me it seems like that std::optional is much more expressive. When using a pointer, you can never be really sure if the option of a nullptr is intended.
|
That guideline is not listing things in order of "pick this first". It is listing options that are appropriate in different situations, and leaves it up to you which is most appropriate for your situation.
In particular, choosing between (const)T* and std::optional<T> is the same as choosing between (const)T& and T. Adapting the examples of the enclosing rule, you'd have
// optional<int> is cheap to copy, pass by value
optional<int> multiply(int, optional<int>);
// suffix is optional and input-only but not as cheap as an int, pass by const*
string& concatenate(string&, const string* suffix);
Aside: If you follow the other guidelines, then you can be sure that a pointer indicates a situation where "no value" is an expected case.
|
74,460,102
| 74,461,001
|
How can I print a diagonal matrix in Eigen
|
I was reading this post and when I was replicating it using
#include <iostream>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
int main(){
Eigen::DiagonalMatrix<double, 3> M(3.0, 8.0, 6.0);
std::cout << M << std::endl;
return 0;
}
I get the error
error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Eigen::DiagonalMatrix<double, 3>')
std::cout << M << std::endl;
~~~~~~~~~ ^ ~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/usr/include/c++/v1/cstddef:143:3: note: candidate function template not viable: no known conversion from 'std::ostream' (aka 'basic_ostream<char>') to 'std::byte' for 1st argument
operator<< (byte __lhs, _Integer __shift) noexcept
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/usr/include/c++/v1/ostream:748:1: note: candidate function template not viable: no known conversion from 'Eigen::DiagonalMatrix<double, 3>' to 'char' for 2nd argument
operator<<(basic_ostream<_CharT, _Traits>& __os, char __cn)
^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/usr/include/c++/v1/ostream:781:1: note: candidate function template not viable: no known conversion from 'Eigen::DiagonalMatrix<double, 3>' to 'char' for 2nd argument
operator<<(basic_ostream<char, _Traits>& __os, char __c)
^
and a few more lines like this. I complied it using the CMakeLists.txt file
cmake_minimum_required(VERSION 3.0)
project(ExternalLib CXX)
set(CMAKE_CXX_STANDARD 17)
find_package(Eigen3 REQUIRED)
add_executable(out main.cpp)
target_link_libraries(main PUBLIC)
Can anyone help me understand what might be the issue here? Thanks in advance!
|
In order to print the matrix you have to cast your DiagonalMatrix to a DenseMatrixType, for example by doing:
std::cout << static_cast<Eigen::Matrix3d>(M) << std::endl;
Or by using the toDenseMatrix method:
std::cout << M.toDenseMatrix() << std::endl;
|
74,461,244
| 74,461,644
|
glfwInit() causes segmentation fault with exit code -1073741515 (0xc0000135)
|
I have been trying to get one my older projects to work which uses some OpenGL code. I am unable to produce a working executable. All that happens is, just by calling glfwInit(), is a segmentation fault:
My best guess is that it somehow doesnt use/find the glfw dll i am trying to use.
Let me explain my current setup:
I have installed glfw using msys2:
pacman -S mingw-w64-x86_64-glfw
I have created a glad header and source file
I wrote a simple cmake-file (which also used to work 2 years ago)
cmake_minimum_required(VERSION 3.23)
project(2DGameEngine)
find_package(glfw3 3.3 REQUIRED)
find_package(OpenGL REQUIRED)
set(CMAKE_CXX_STANDARD 23)
file(GLOB_RECURSE SRCS src/*.cpp src/*.c)
add_executable(2DGameEngine ${SRCS})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wshadow")
target_link_libraries(2DGameEngine glfw)
target_link_libraries(2DGameEngine OpenGL::GL)
I used the simplest example I could find:
#include "glad.h"
#include <GLFW/glfw3.h>
#include <iostream>
int main()
{
// glfw: initialize and configure
// ------------------------------
if(!glfwInit()){
std::cout << "error" << std::endl;
exit(1);
}
return 0;
}
Yet I am unable to get rid of the segmentation fault when calling glfwInit(). I assume it has to do with some .dll missing but I have no idea how I could check this. I am very happy for any help.
|
0xc0000135 is the error you get when your Windows OS could not find a required dll when executing your program. There is a handy site that decodes these types of errors here: https://james.darpinian.com/decoder/?q=0xc0000135
Use this program: https://github.com/lucasg/Dependencies to figure out what dll can not be found and then put that dll in the same folder as the executable or edit your OS PATH environment variable to contain the folder which has that dll.
Here is a good article on how to set the OS PATH environment variable: https://www.computerhope.com/issues/ch000549.htm
There are several other options contained in this Microsoft document which explains how and where your OS searches for dlls: https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order#search-order-for-desktop-applications
|
74,462,470
| 74,463,213
|
If there are many threads are waiting to be notify, which one does the std::condition_variable::notify_one() function notify?
|
I am writing a c++ multithread program, which have more than one thread wait to be notify.
std::mutex mutex;
std::condition_variable cv;
bool is_prepared = false;
bool is_fornt_left_finished = false;
bool is_fornt_right_finished = false;
bool is_back_left_finished = false;
thread t1(&Underpan::FrontLeft, this), t2(&Underpan::FrontRight, this),
t3(&Underpan::BackLeft, this), t4(&Underpan::BackRight, this);
is_prepared = true;
t1.join();
t2.join();
t3.join();
t4.join();
cv.notify_one(); // fail
// cv.notify_all(); // success
I originally thought that the order of notify is the order of thread construction. But in actual operation, the program can be successfully run occasionally, and the program will be blocked occasionally.
I‘v e checked the official documents and didn't explain this part of the details.
Whether the sequence is unpredictable or not?
|
It is unspecified which thread will be woken up. There doesn't need to be any particular rule to it. There doesn't need to be any "sequence" either. It could just always keep waking up the same thread (as long as it is always waiting when the notification happens) and it could also randomly wake up a different thread.
Of course the particular standard library implementation may make some guarantee, but I don't think it is likely that it will. Practically the implementation will likely just use whatever approach is the most efficient for implementing std::condition_variable and uncertainty from the operating system's management of the threads will also play into it.
So don't write any code that relies in any way on which thread will be woken up.
|
74,462,835
| 74,463,025
|
How can someone else be able to run my C++ project if I use SFML libraries?
|
I'm new to C++ programming and am working on a Pong game. I want to use SFML libraries, but I want to send the project to a friend. Will he be able to run the project without errors if he does not have SFML installed?
Note: I want to send it as a Visual Studio project, not as an executable.
|
You can just make a "libraries" folder to your project file and add there the SFML folder.
After doing that open the SFML folder and go to the bin folder and copy all the .dll files you see.
Then paste the dll files to the folder your vs files are (.vcxproj etc)
|
74,462,888
| 74,477,308
|
AES Encryption with EasyCrypto C# and Decryption in C++ using Crypto++
|
I have encrypted a string using EasyCrypto in C# using the following code
Encryption C#:
/*
EasyCrypto encrypted key format from CryptoContainer.cs file from the EasyCrypto source on GitHub.
* Format:
* 04 bytes 00 - MagicNumber
* 02 bytes 04 - DataVersionNumber
* 02 bytes 06 - MinCompatibleDataVersionNumber
* 16 bytes 08 - IV
* 32 bytes 24 - Salt
* 19 bytes 56 - Key check value
* 48 bytes 75 - MAC
* 04 bytes 123 - Additional header data length
* xx bytes 127 - Additional data
* ----- end of header ----- (sum: 127)
* xx bytes - additional header data (0 for version 1)
* xx bytes - data
*/
AesEncryption.EncryptWithPassword("data to encrypt", "password string");
/*
Method Description:
Encrypts string and returns string. Salt and IV will be embedded to encrypted string. Can later be decrypted with
EasyCrypto.AesEncryption.DecryptWithPassword(System.String,System.String,EasyCrypto.ReportAndCancellationToken)
IV and salt are generated by EasyCrypto.CryptoRandom which is using System.Security.Cryptography.Rfc2898DeriveBytes.
IV size is 16 bytes (128 bits) and key size will be 32 bytes (256 bits).
/*
I am trying to decrypt in C++ using Crypto++, using the following code. I am just getting the error "ciphertext length is not a multiple of block size", what is the missing part in the code? any help would be highly appreciable.
Decryption C++:
string Decrypt() {
// getting CryptoPP::byte array from passowrd
string destination;
CryptoPP::StringSource ss(<hex of password string>, true, new CryptoPP::HexDecoder(new CryptoPP::StringSink(destination)));
CryptoPP::byte* keyByteArray = (CryptoPP::byte*)destination.data();
// getting CryptoPP::byte array from encoded data
string pkDst;
CryptoPP::StringSource ss2(<hex of encoded data>, true, new CryptoPP::HexDecoder(new CryptoPP::StringSink(pkDst)));
CryptoPP::byte* pkByteArray = (CryptoPP::byte*)pkDst.data();
// getting initialization vector from encoded data
CryptoPP::byte iv[16];
for (int i = 8; i < 24; i++) {
iv[i] = pkByteArray[i];
}
string result = CBCMode_Decrypt(keyByteArray, 32, iv);
return result;
}
string CBCMode_Decrypt(CryptoPP::byte key[], int keySize, CryptoPP::byte iv[]) {
string recovered = "";
//Decryption
try
{
CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption d;
d.SetKeyWithIV(key, keySize, iv);
// The StreamTransformationFilter removes
// padding as required.
CryptoPP::StringSource s("encoded string", true, new CryptoPP::StreamTransformationFilter(d, new CryptoPP::StringSink(recovered))); // StringSource
}
catch (const CryptoPP::Exception& e)
{
cerr << e.what() << endl;
exit(1);
}
return recovered;
}
|
In the Crypto++ code, the following steps must be performed for decryption:
Base64 decoding of the EasyCrypto data
Separating IV, salt and ciphertext (using the information from the CryptoContainer.cs file)
Deriving the 32 bytes key via PBKDF2 using salt and password (digest: SHA-1, iteration count: 25000)
Decryption with AES-256 in CBC mode and PKCS#7 padding (using key and IV)
A possible Crypto++ implementation is:
#include "aes.h"
#include "modes.h"
#include "pwdbased.h"
#include "sha.h"
#include "base64.h"
using namespace CryptoPP;
using namespace std;
...
// Base64 decode data from EasyCrypto
string encoded = "bqCrDAQABABtXsh2DxqYdpZc6M6+kGALOsKUHzxoMR6WAVg5Qtj3zWbr4MiEBdqt9nPIiIZAynFAZmweHQPa/PhEItR6M8Jg1bHAYeQ8Cm5eUlKNzPXFNfuUw0+qtds29S0L4wAWY0xfuiBJTUeTJuSLWqoirm/rHGOWAAAAAKtBivUDvxta1d0QXE6J9x5VdSpAw2LIlXARKzmz+JRDtJcaj4KmGmXW/1GjZlMiUA==";
string decoded;
StringSource ssB64(
encoded,
true,
new Base64Decoder(
new StringSink(decoded)
)
);
// Separate IV, salt and ciphertext
string ivStr = decoded.substr(8, 16);
string saltStr = decoded.substr(24, 32);
string ciphertextStr = decoded.substr(127);
// Derive 32 bytes key using PBKDF2
char password[] = "my passphrase";
unsigned int iterations = 25000;
byte key[32];
size_t keyLen = sizeof(key);
PKCS5_PBKDF2_HMAC<SHA1> pbkdf;
pbkdf.DeriveKey(key, keyLen, 0, (byte*)password, sizeof(password), (byte*)saltStr.c_str(), saltStr.length(), iterations, 0.0f);
// Decrypt with AES-256, CBC, PKCS#7 padding
string decrypted;
CBC_Mode<AES>::Decryption decryption(key, keyLen, (byte*)ivStr.c_str());
StringSource ssDec(
ciphertextStr,
true,
new StreamTransformationFilter(
decryption,
new StringSink(decrypted),
BlockPaddingSchemeDef::BlockPaddingScheme::PKCS_PADDING
)
);
// Output
cout << "Decrypted: " << decrypted << "\n";
with the output:
Decrypted: The quick brown fox jumps over the lazy dog
The ciphertext was generated with EasyCrypto:
AesEncryption.EncryptWithPassword("The quick brown fox jumps over the lazy dog", "my passphrase");
The previous section focused on decryption. Note, however, that for security reasons, authentication is required before decryption and decryption may only be performed on successfully authenticated data.
For authentication also the MAC must be determined in addition to IV, salt and ciphertext. EasyCrypto applies an HMAC-SHA-384 as MAC. Only the ciphertext is used to determine the MAC, and the key for authentication is the same as the key for encryption.
For authentication, the calculated and the sent MAC must be compared. If both are the same, the authentication is successful (and the decryption can be performed).
A possible Crypto++ implementation for the authentication is:
// Get the sent MAC
string macSentStr = decoded.substr(75, 48);
// Calculate the MAC using ciphertext and encryption key
string macCalcStr;
HMAC<SHA384> hmac(key, keyLen);
StringSource ssMac(
ciphertextStr,
true,
new HashFilter(hmac,
new StringSink(macCalcStr)
)
);
// Compare both MACs
cout << (!macSentStr.compare(macCalcStr) ? "Authentication successful" : "Authentication failed") << endl; // compare returns 0 if both strings match
which successfully authenticates the sample data.
|
74,463,290
| 74,467,080
|
Dynamically binding of overridden methods
|
I'm trying to understand when the compiler has, or not, all the information needed to decide statically or dynamically how to bind method calls to method definitions.
I read that in Java there is a rule that binds them statically when the method is overloaded and dynamically when it is overridden. I'm playing around with some C++ code and it's not clear to me how it works.
For example, if I have:
class A
{
public:
// virtual void p()
void p() {
cout << "A::p" << endl;
}
void q() {
p();
}
};
class B : public A
{
public:
void p() {
cout << "B::p" << endl;
}
};
a) When I do:
A a;
B b;
a.q(); // output: A::p
b.q(); // output: A::p
I assume the compiler (g++) binds statically b.q() to A.q() and p() (inside A.q()) to A.p(). A.p() is into the context of A.q()
b) But, if I declare A.p() as virtual, the output will be:
a.q(); // output: A::p
b.q(); // output: B::p
Here, I imagine that, b.q() is bound to A.q(), statically as did the previous scenario, but p() inside A.q() is bound to B.p(), that override A.p().
If the rule were the same (that overriding is resolved dynamically), it would imply that the compiler does not have all the necessary information to do it statically.
Why can't the compiler bind the overridden version of the virtual method instead of deferring that decision to the runtime? Which is the lacking information here?
===> Edited <===
It was suggested not to mix Java and C++. I'm reading the Louden & Lambert book "Programming Languages" and the authors compare what bindings look like in both languages. That is the reason why I mentioned them. But, my question is more related to the need for dynamic linking, regardless of language. Why can't the compiler figure out based on the source code how to bind virtual or overridden methods?
|
C++ uses virtual method tables to support dynamic dispatch.
An instance of a class contains a hidden pointer to a struct containing the function pointers
for the virtual methods for that class.
For a simple example:
class A {
public:
virtual void p();
};
void some_function(A* ap) {
ap->p();
}
The compiler has no idea ahead of time what code the call to ap->p(); will actually invoke.
some_function could be compiled into object code, sitting in a library or
linked to an executable, run and invoke ap-p>();, and execute code that
literally didn't exist at the time some_function was compiled.
|
74,463,353
| 74,470,698
|
emplace pointer as proper type into std::variant in template
|
Is it possible to emplace some void* pointer into variant with a runtime generated index.
Can this nice solution (from here link), be updated to get index and pointer to emplace?
#include <variant>
template <typename... Ts, std::size_t... Is>
void next(std::variant<Ts...>& v, std::index_sequence<Is...>)
{
using Func = void (*)(std::variant<Ts...>&);
Func funcs[] = {
+[](std::variant<Ts...>& v){ v.template emplace<(Is + 1) % sizeof...(Is)>(); }...
};
funcs[v.index()](v);
}
template <typename... Ts>
void next(std::variant<Ts...>& v)
{
next(v, std::make_index_sequence<sizeof...(Ts)>());
}
It is possible to get the required data type, but don't think it helps anyway
Func funcs[] = {
[](MessageTypesVariant& v) {
auto y = std::get<(Is)>(v);
auto z = std::forward<decltype(y)>(y);
v.template emplace<(Is)>(); }...
};
|
You can do it like this, unpack Ts... and check if the type matches.
template <typename T, typename... Ts>
bool set(std::variant<Ts*...>& v, int typeIndex, void* ptrToData) {
constexpr static auto idx = index_v<T, Ts...>;
if (idx == typeIndex) {
v.template emplace<idx>(static_cast<T*>(ptrToData));
return true;
}
return false;
}
template <typename... Ts>
void set(std::variant<Ts*...>& v, int typeIndex, void* ptrToData) {
(set<Ts, Ts...>(v, typeIndex, ptrToData) || ...);
}
Here, you need a way to index a type from a typelist, index_v, a common tech used in typelist.
// index
inline constexpr std::size_t npos = -1;
template <typename T, typename... Ts>
struct index : std::integral_constant<std::size_t, npos> {};
template <typename T, typename... Ts>
inline constexpr std::size_t index_v = index<T, Ts...>::value;
template <typename T, typename... Ts>
struct index<T, T, Ts...> : std::integral_constant<std::size_t, 0> {};
template <typename T, typename Head, typename... Tail>
class index<T, Head, Tail...> {
static constexpr std::size_t tmp = index_v<T, Tail...>;
public:
static constexpr std::size_t value = tmp == npos ? tmp : tmp + 1;
};
Demo
|
74,463,881
| 74,463,973
|
C++ vector not saving the parent of an object
|
Suppose I Have class A like this
class A {
public:int num;
public:A* parent;
A(){};
A::A (const A &s)
{
this->num = s.num;
}
};
Inside the main function I make two object from class A
int main()
{
A a1;
a1.num = 2;
A a2 = a1;
a2.parent = &a1;
cout << a2.parent->num << endl;
return 0;
}
it will obviously print 2 but when I make a vector of class A and push a2 object into the vector like this
int main()
{
A a1;
a1.num =2;
A a2 = a1;
a2.parent = &a1;
vector <A> List;
List.push_back(a2);
A temp = List.front();
cout << temp.parent->num << endl;
return 0;
}
cmd is crashing and its not printing anything . Could anyone help me .
PS: I didn't know what is the correct way to assign the second object into the parent of the first object inside the deep copy constructor that's why I assigned it manually .
|
Your problem is here:
A::A (const A &s)
{
this->num = s.num;
}
This is a copy constructor. It is triggered on A temp = List.front();
However, it doesn't set this->parent, which remains uninitialized. So, next line, when you do temp.parent->num you access uninitialized memory.
You should also do: (Or remove it altogether as Some Programmer dude suggests)
A::A (const A &s)
{
this->num = s.num;
this->parent = s.parent;
}
But take some time to look up on the rule of three. And know that vectors will reallocate and may invalidate the address of some objects. This will come to bite you if you set an object from a vector as a parent of another one.
|
74,463,919
| 74,464,104
|
Variable Length Array elements random generator
|
simple task, to generate arrays with length I want to.
I don't also know how to get array I've created, except my own weird method. Does the first part of my code work alright and I should reconsider the way I want to get them (optional)?
although, I do understand why do I get the same values each time, but I don't think, it's related to my problem somehow.
I'm writing down this:
cin >> x;
int array1[x];
int array2[x];
for (int i = 0; i <= x; i++) {
array1[i] = rand() % 10 + 1;
array2[i] = rand() % 10 + 1;
}
cout << "[" << array1[a];
for (int a = 0; a <= x; a++) {
a += 1;
cout << ", " <<array1[a];
}
cout << "] [" << array2[b];
for (int b = 0; b <= x; b++) {
b += 1;
cout << ", " << array2[b];
}
cout << "]";
why do i get some abnormal answer for x = 6, 5, 15 cases like this:
[2, 5, 9, 6, 0] [8, 1, 9, 6, 32759]
[2, 5, 9, 6, 2, 8, 3, 2, 8] [8, 1, 9, 6, 2, 7, 4, 7, 7]
|
Or using header and std::vector, std::generate (no raw loop).
Also when you write code, write small readable functions.
And to get unique random numbers random generators need to be seeded.
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
int generate_random_number()
{
// only initialize the generator and distribution once (static)
// and initialize the generator from a random source (device)
static std::mt19937 generator(std::random_device{}());
static std::uniform_int_distribution<int> distribution{ 1,10 };
return distribution(generator);
}
// overload stream output for vector, so we can use vectors in std::cout
std::ostream& operator<<(std::ostream& os, const std::vector<int>& values)
{
bool comma{ false };
os << "[";
for (const int value : values)
{
if (comma) os << ", ";
os << value;
comma = true;
}
os << "]";
return os;
}
// helper function to create an array of given size
std::vector<int> create_random_array(const std::size_t size)
{
std::vector<int> values(size); // create and allocate memory for an array of size ints
std::generate(values.begin(), values.end(), generate_random_number); // fill each value in the array with a value from the function call to generate_random_number
return values;
}
int main()
{
std::size_t count;
std::cout << "how many random numbers ? : ";
std::cin >> count;
auto array1 = create_random_array(count);
std::cout << array1 << "\n";
auto array2 = create_random_array(count);
std::cout << array2 << "\n";
return 0;
}
|
74,464,115
| 74,464,168
|
Segmentation fault in linked list c++
|
I can't seem to get rid of segmentation fault in 2 places.
This is the whole code. I would be so grateful if someone could let me know why it isn't working and how can I make it work
#include <iostream>
template <typename Key, typename Info>
class Sequence
{
private:
struct Node
{
Key key;
Info info;
Node *next;
};
Node *head;
public:
Sequence<Key, Info>() { head = NULL; };
~Sequence<Key, Info>(){};
void print();
void pushBack(Key key, Info info);
};
template <typename Key, typename Info>
void Sequence<Key, Info>::pushBack(Key key, Info info)
{
Node *ptr;
ptr = new Node;
ptr->key = key;
ptr->info = info;
if (head)
{
Node *temp = head;
while (temp->next != NULL) // here there is segmentation fault
{
temp = temp->next;
}
temp->next = ptr;
}
else
{
head = ptr;
}
}
template <typename Key, typename Info>
void Sequence<Key, Info>::print()
{
if (head != NULL)
{
Node *ptr = head;
while (ptr->next != NULL) // segmentation fault happens here too
{
std::cout << ptr->info << std::endl;
ptr = ptr->next;
}
}
else
{
std::cout << "Empty sequence" << std::endl;
}
}
int main()
{
Sequence<int, int> seq;
seq.pushBack(1, 5);
seq.pushBack(2, 6);
seq.print();
}
I tried many solutions proposed online but none of them seemed to work for me. I would be grateful if you could look at it
|
You forgot to set next
Node *ptr;
ptr = new Node;
ptr->key = key;
ptr->info = info;
ptr->next = NULL; // <--- here
Honestly it would be better if you looked at your own code rather than looking online. Especially you should learn how to use a debugger. If you were experienced at using a debugger you would have found this error in minutes.
|
74,464,611
| 74,466,697
|
Move few elements from list to a vector
|
I am planning to move some elements from a list to the target container(say vector) for further processing. Is it safe to use move_iterator for moving to target And erase the moved section of the source container?
#include<list>
#include<vector>
#include<iterator>
struct DataPoint {};
int main() {
std::list<Datapoint> d_data; // source
std::vector<Datapoint> v2; // target
v2.insert(v2.end(),
std::make_move_iterator(d_data.begin()),
std::make_move_iterator(d_data.begin() + size)
);
d_data.erase(d_data.begin(), d_data.begin() + size); // safe? necessary?
//...
//d_batch->addData(v2);
return 0;
}
|
You may find std::move easier to use.
And yes, you do need to erase the moved elements in the source container.
[Demo]
#include <algorithm> // move
#include <fmt/ranges.h>
#include<list>
#include<vector>
#include<iterator> // back_inserter
int main() {
std::list<int> l{1, 2, 3, 4, 5}; // source
std::vector<int> v; // target
auto begin_it{std::next(l.begin())};
auto end_it{std::prev(l.end())};
std::move(begin_it, end_it, std::back_inserter(v));
fmt::print("l before erase: {}\n", l);
l.erase(begin_it, end_it);
fmt::print("l after erase: {}\nv: {}\n", l, v);
}
// Outputs:
//
// l before erase: [1, 2, 3, 4, 5]
// l after erase: [1, 5]
// v: [2, 3, 4]
|
74,464,890
| 74,466,164
|
Is there an objective reason why the explicitly instantiated std::less, std::greater and similar offer no conversion to function pointer?
|
Stateless lambdas can be converted to function pointers, e.g. this is valid,
using Fun = bool(*)(int, int);
constexpr auto less = [](int a, int b){ return a < b; };
Fun f{less};
but objects like std::less<int>{} can't.
I do understand why std::less<>{} can't, because it's operator() is not instantiated until the object is applied to some arguments, so how could it be converted to a Fun, if the decision of what its template argument(s) are is not been taken yet?
But std::less<int>{} seems just the same as the lambda I've written above, no?
|
Stateless lambdas can be converted to function pointers, e.g. this is valid, [...] but objects like std::less<int>{} can't.
"Can't" is the wrong word. After all, a "stateless lambda" is just an object, and it doesn't have any magical rules compared to other objects. A lambda is a class type like any other. It is simply generated by the compiler. You can hand write a type that does anything a lambda does; it'd just take more code.
The ability of stateless lambdas to be converted to function pointers is similarly not magic. Any type can have conversion operators defined for it, allowing them to be implicitly convertible to arbitrary types. For a stateless lambda, the compiler simply generates a conversion operator to a pointer to an appropriate function pointer signature.
std::less<T> could have an operator bool (*)(T const&, T const&)() const overload that returns a pointer to a function that does this comparison. But it doesn't. There's nothing stopping it from doing this, save the fact that the C++ standard doesn't say that the type shall have such an interface.
And this hasn't happened because nobody has proposed it for standardization.
|
74,465,379
| 74,465,557
|
What is the use for this Condition in the for loop for(int i = 0; i < m and n; i++)?
|
I encountered a question in competitive programming and the solution for that include a for loop with a syntax like
for(int i = 0; i < m and n; i++){
//Do Something
}
When I changed the condition from i < m and n to i < m and submitted the solution it was giving TLE whereas in the i < m and n condition the Solution was Accepted.
What is the use of i < m and n condition if the loop runs only m times? And I don't feel like m would exceed n (if the answer is it looks for both the variables in an and comparison). What is the impact in time Complexities?
|
According to the C++ Standard (for example C++ 14 Standard4,section 12 Boolean conversions)
1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
to member type can be converted to a prvalue of type bool. A zero
value, null pointer value, or null member pointer value is converted
to false; any other value is converted to true. For
direct-initialization (8.5), a prvalue of type std::nullptr_t can be
converted to a prvalue of type bool; the resulting value is false.)
So this expression
i < m and n
is equivalent to
i < m and n != 0
that is the same as
i < m && n != 0
or if to make it more clear
( i < m ) && ( n != 0 )
and in the expressipn is an alternative representation of the logical AND operator &&.
It seems that within the body of the loop (or before the loop) the variable n can be changed and as a result can be equal to 0. In this case the loop will be interrupted even if i is less than m.
|
74,465,629
| 74,466,597
|
C++ Vector Returned from function not printing right values
|
I have class A and a main() function:
class A {
public: int num;
public: A* parent;
A(){};
A::A (const A &s)
{
this->num = s.num;
this->parent = s.parent;
}
public : vector <A> foo(A a)
{
A a1;
a1.num = a.num;
a1.parent = &a;
vector <A> list;
list.reserve(1);
list.push_back(a1);
A temp = list.front();
cout << temp.parent->num << endl;
return list;
}
};
int main()
{
A a;
a.num =2;
vector <A> list = a.foo(a);
A temp = list.front();
cout << temp.parent->num << endl;
return 0;
}
The problem is that cout inside foo() prints 2 as expected, but cout inside main() is printing a huge number.
I assume the problem is something related to memory rellocation, as I read from multiple sources, so I tried using reserve() but it didn't work.
Can anyone help me solve this problem?
|
In foo(), you are passing in the a parameter by value. That means the A object that main() is passing to foo() gets copied into the a parameter. The a parameter itself is a local variable to foo(). As such, a1.parent is being set to point at a local variable.
And then list.push_back(a1); makes a copy of a1, which copies the parent pointer. And then you are making another copy when saving the result of list.front() to temp.
Consequently, dereferencing the temp.parent pointer inside of foo() is perfectly valid, since a that parent is pointing at is still valid in memory.
However, once foo() exits, a gets destroyed, leaving the copied parent pointer(s) dangling, pointing at now-invalid memory. As such, in main(), dereferencing the parent pointer is undefined behavior since that pointer is no longer pointing at the original a object.
You can easily see this for yourself if you add some logging for the construction and destruction of your A objects, eg:
class A {
public:
int num = 0;
A* parent = nullptr;
A(){ cout << "A created: " << this << endl; }
A(const A &s) : num(s.num), parent(s.parent)
{
cout << "A copied: " << &s << " -> " << this << endl;
}
~A(){ cout << "A destroyed: " << this << endl; }
...
};
Online Demo
You will see something like this being logged:
A created: 0x7ffe5e735250 // 'a' in main() is created
A copied: 0x7ffe5e735250 -> 0x7ffe5e735260 // 'a' in foo() is passed in by main()
A created: 0x7ffe5e7351e0 // 'a1' in foo() is created
A copied: 0x7ffe5e7351e0 -> 0x5592f50b2e80 // 'a1' is copied into `list` in foo()
A copied: 0x5592f50b2e80 -> 0x7ffe5e7351f0 // list.front() is copied into 'temp' in foo()
(foo) temp.parent: 0x7ffe5e735260, num: 2 // parent is pointing at 'a' in foo()
// foo() exits, 'list' is transferred to main()
A destroyed: 0x7ffe5e7351f0 // 'temp' in foo() is destroyed
A destroyed: 0x7ffe5e7351e0 // 'a1' in foo() is destroyed
A destroyed: 0x7ffe5e735260 // 'a' in foo() is destroyed !!!!!
A copied: 0x5592f50b2e80 -> 0x7ffe5e735260 // main() reuses freed memory for 'temp' in main() !!!!!
(main) temp.parent: 0x7ffe5e735260, num: 2 // parent is pointing at the wrong A object !!!!!
// main exits
A destroyed: 0x7ffe5e735260 // 'temp' in main() is destroyed
A destroyed: 0x5592f50b2e80 // `list` in main() is destroyed
A destroyed: 0x7ffe5e735250 // 'a' in main() is destroyed
To solve this issue, change foo() to take in the A object by reference instead (and also change the two temp variables to be A& references, as well):
vector<A> foo(A &a)
This way, in main(), the returned parent pointer will remain valid as long as the local a object that is being passed into foo() remains valid.
Online Demo
Now, you will see something like this being logged instead:
A created: 0x7ffd7319e8b0 // 'a' in main() is created
// 'a' in foo() is passed in by main()
A created: 0x7ffd7319e850 // 'a1' in `foo() is created
A copied: 0x7ffd7319e850 -> 0x556ccff0fe80 // 'a1' is copied into 'list' in foo()
(foo) temp.parent: 0x7ffd7319e8b0, num: 2 // parent is pointing at 'a' in main()
// foo() exits, 'list' is transferred to main()
A destroyed: 0x7ffd7319e850 // 'a1' in foo() is destroyed
(main) temp.parent: 0x7ffd7319e8b0, num: 2 // parent is still pointing at 'a' in main()
// main() exits
A destroyed: 0x556ccff0fe80 // 'list' in main() is destroyed.
A destroyed: 0x7ffd7319e8b0 // 'a' in main() is destroyed !!!!!
|
74,465,957
| 74,466,064
|
How to find elements of a string that cannot be part of a non contigous substring?
|
I want to write a program that takes 2 strings as input, s1 and s2, and determines which characters of s1 couldn't be part of a non contigous substring that is 2. So after inputting
123625421454 as s1, and 254 as s2, the program would output
0 1 0 0 1 1 1 1 0 1 1 1, where 1 means that a character can be a part of the substring, and 0 where it cannot.
This problem is really irritating me, since I couldn't find any algorithm that would find the non-contigous sequence without extremely high execution time. Is there even a good solution for this, with less or equal O than O(N)?
I have tried to use hashes and dynamic programming, but no algorithms that I used were good for this circumstance.
EDIT: To clarify, the idea is that you can remove x elements of s1 (x can be 0) and get s2. Elements, which cannot be part of s2 under any circumstances, should be marked as 0, while those that can, should be marked as 1. Hope this helps.
|
A key observation is, if you reach a sub-substring prefix of length k up to a position, then you can have a sub-substring of any length less than k up to that position, simply by skipping some of the tail elements. Same holds for postfix. It might sound trivial, but it leads to the solution.
So you'd like to maximize the prefix from front and postfix from tail. Basically, this means that you visit s1 once from front and once the reverse (with reverse s2). In both cases, you'd like to maximize the substring at each point, so you simply advance in s2 whenever you can. This gives you two array of size_t values: longest possible prefix and postfix at the given point. If the sum of those >= the length of s2 (and there was an increase at the current character in prefix/postfix arrays compared to previous), that means that these can be joined and the result is 1; otherwise these cannot be joined and the result is 0.
To do this, you actually need to precalculate if a given char can be an increase at a position in s2. This can be done in O(1) time (see chat for elaboration on that).
|
74,466,059
| 74,466,330
|
unique_ptr is copying when raw pointer is passed into its constructor
|
I am trying to understand how unique pointers work in modern C++.
When I went through the documentations (cppreference and others), I was able to understand that unique_ptr will transfer ownership and not share it. But I am not able to understand why unique_ptr is acting strange when working with a raw pointer passed into its constructor.
For example:
#include <iostream>
#include <memory>
class foo{
int x;
public:
foo(): x(0) {}
foo(int a): x(a) {}
foo(const foo& f): x(f.x) {}
};
int main(){
foo *ptr = new foo(5);
std::unique_ptr<foo> uptr(ptr);
std::cout << ptr << "\n";
std::cout << uptr.get() << "\n";
return 0;
}
Output below:
0x5c7bc80
0x5c7bc80
Queries:
Is the raw pointer being passed into the copy constructor? Isn't the copy constructor deleted (=delete)? Why is the raw pointer printing the same address as unique_ptr?
Is this a design flaw of unique_ptr?
How do I overcome this issue?
What is the use of std::make_unique()? I tried changing the line std::unique_ptr<foo> uptr(ptr); to std::unique_ptr<foo> uptr(std::make_unique<foo>(*ptr)); but nothing changed.
|
Is the raw pointer being passed into the copy constructor?
Not the copy constructor, no (that takes another unique_ptr as input). The raw pointer is being passed to a converting constructor instead, specifically this one in this case:
explicit unique_ptr( pointer p ) noexcept;
Isn't the copy constructor deleted (=delete)?
Yes. But this code is not invoking the copy constructor.
Why is the raw pointer printing the same address as the unique_ptr?
Because the unique_ptr is simply copying the input pointer as-is into its own internal member pointer, taking ownership of the object that is being pointed at. You are printing the value of the two pointers, and they have the same value because they are pointing at the same object in memory.
Is this a design flaw of unique_ptr?
No.
How do I overcome this issue?
What issue? There is no issue here. The unique_ptr is acting as designed.
What is the use of std::make_unique()?
To more efficiently allocate memory, construct an object in that memory, and take ownership of that memory with a new unique_ptr, all in one operation.
I tried changing the line std::unique_ptr<foo> uptr(ptr); to std::unique_ptr<foo> uptr(std::make_unique<foo>(*ptr)); but nothing changed.
It should have.
The expression std::make_unique<foo>(*ptr) is creating a new foo object that is separate from the object that ptr is pointing at. It will pass the dereferenced *ptr object to the new foo object's copy constructor.
And then, in the expression std::unique_ptr<foo> uptr(...);, uptr is moving the unique_ptr that make_unique() returns, which is pointing at the new foo object. So uptr now owns that foo object.
Subsequently, your 2 prints should be outputting different values, since ptr and uptr are pointing at different foo objects.
Note that in this situation, you would be leaking the foo object that ptr is pointing at, since no unique_ptr is taking ownership of that object. So you are responsible for delete'ing it manually.
This code:
foo *ptr = new foo(5);
std::unique_ptr<foo> uptr(ptr);
Can be changed to this instead:
std::unique_ptr<foo> uptr = std::make_unique<foo>(5);
or:
auto uptr = std::make_unique<foo>(5);
std::make_unique() allocates and constructs the type specified in its template argument, passing the input parameters to that object's constructor.
|
74,466,363
| 74,466,476
|
incorrect data in array index - what will happen?
|
I found a mistake I made in my code associated with indexing an array.
It compiled and I didn't notice the issue for some time. I'm curious what the index really was.
Intended code:
if(arr[i] > 3){//do stuff}
what was written:
if(arr[i > 3]){//do stuff}
what did the array index end up being?
|
In reality, what happens is very simple.
In the first case, the if checks each element of the array and sees if it is greater than 3.
In the second case, it's more complex than it seems. In practice, as long as the i is greater than 3, the index taken will be 1, as it satisfies the equation x > 3, otherwise I take the index 0.
In practice it is the transformation of the boolean value into an integer value. Once it takes the index, the if does nothing but be true if the value is non-zero, otherwise if the value inside the array is 0 it will be false.
A very practical example for the second problem would be:
int arr[4] = {1,2,3,4};
cout << arr[2 > 4] << endl; //The output would be 1, since 2 > 4 would be false and would return 0 as a result.
Sorry if I made a bad explanation but I tried my best :)
|
74,466,912
| 74,466,958
|
What does 'dict' do in c++?
|
I was looking at a solution for this problem:
Given a string s, find the length of the longest substring without repeating characters.
The following solution was posted, but I am having trouble understanding what dict does. I've tried looking for documentation in C++. However, I have not found anything. Can someone explain how it works, and where I can find documentation?
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
|
dict is just the name that was used for this vector<int>, first parameter is the the size of vector, second is value that should be assigned to all of its positions.
This is one of the possible ways to use its constructor, check the example on this page.
|
74,466,943
| 74,468,206
|
How to package several icons for different sizes in a VS C++ app?
|
I'm developing a C++ app in Visual Studio 2022 with a UI (UI library is wxWidgets). I'm trying to figure out how icons work. I gathered from researching that Windows expects a variety of different icons to be packaged with apps for the best UX (see Which icon sizes should my Windows application's icon include?). However I can't seem to find a way to get multiple icons taken into account.
My understanding so far is that all resource related things, including icons, are controlled by Resource.h and <projectName>.rc, both of which are initially provided by the VS template for a C++ App.
I've removed the provided icons (i.e the "normal" and "small" ones) and have instead imported many icons, one for each size, in the Resource View.
But regardless of that, always one icon seem to be used at a time.
Checking the contents of <projectName>.rc, I see the following:
I also expect the following, in Resource.h, to be relevant:
It seems that independently of the icon sizes, IDI_ICON1 is used. If it's 16x16, it's upscaled in context that requires it, if it's 256x256, it's downscaled (poorly, somehow ?) when required i.e in almost all contexts.
How should this be done ? Are there resources available on the matter I may have missed ?
|
You should embed all your ico files with different resolution into one ico file. The ico file is actually a container and can contain multiple images inside.
|
74,468,115
| 74,469,652
|
How to calculate angle of two vectors for determining vertex concavity in ear clipping algorithm
|
I am trying to implement this ear clipping algorithm (from the pseudocode) here Currently at the point in the algorithm where I am trying to calculate the angle of each vertex in a polygon. I also got the idea of how to calculate the angles with vectors here: here This way I can also determine convexity/concavity. Also my vertices are in counter clockwise order.
This is a helper function I wrote to help in calculating the angle of each vertex:
void calcConvexity(Node&* prev, Node&* curr, Node&* next) {
glm::vec2 u(0.0f), v(0.0f);
u.x = curr->x - prev->x;
u.y = curr->y - prev->y;
v.x = curr->x - next->x;
v.y = curr->y - next->y;
// Calculating angle (in radians)
curr->Angle =
((u.x * v.y) - (u.y * v.x))
/
std::sqrt((std::pow(u.x, 2.0f) + std::pow(u.y, 2.0f)) *
std::sqrt(std::pow(v.x, 2.0f) + std::pow(v.y, 2.0f));
// Convert to degrees
curr->Angle = (180 / 3.141592653589793238463) * curr->Angle;
if (curr->Angle < 180.0f)
curr->isConvex = true; // The vertex is convex
else
curr->isConvex = false;
}
I was expecting most of the angles to come out between 0 and 360 but they did not. I am not sure what further calculations or corrections I need to make. Also, in the node class I have a boolean attribute called isConvex. I know something wrong is happening because every vertex is having there isConvex attribute set to true even when there degree is greater than 180.0f (in the example below).
Here is an actual example output as well:
(The blue arrows are suppose to be facing in towards the nodes I just cant update the picture on here)
Polygon With vectors to each vertice
as well as the isConvex values for each node:
Node isConvex Values
and the angles:
Node angle values
I have tried facing the vectors in different directions as well as using the GLM library for vector operations.
I apologize if any of what I have supplied is confusing, this is my first time messing with computational geometry in general. So I am just wondering what am I doing wrong in my calcConvexity method?
UPDATED CODE:
void calcConvexity(Node&* prev, Node&* curr, Node&* next) {
glm::vec2 u(0.0f), v(0.0f);
u.x = curr->x - prev->x;
u.y = curr->y - prev->y;
v.x = curr->x - next->x;
v.y = curr->y - next->y;
float CrossProduct = ((u.x * v.y) - (u.y * v.x));
if (CrossProduct < 0)
curr->isConvex = true; // The vertex is convex
else
curr->isConvex = false; // Otherwise concave
curr->Angle =
(CrossProduct)
/
std::sqrt((std::pow(u.x, 2.0f) + std::pow(u.y, 2.0f)) *
std::sqrt(std::pow(v.x, 2.0f) + std::pow(v.y, 2.0f));
curr->Angle = glm::degrees(std::asin(curr->Angle));
}
So the solution I came up with is this:
I use the Cross product to determine convexity and then I use a slightly different angle formula: cos(curr->Angle) = (u.b) / (|u||v|)
My main problem was the the formula with sin was outputting between -90 and 90 while the formula with cos outputs between 0 and 180
Code that works:
void Graph::calcConvexity(Node*& prev, Node*& curr, Node*& next) {
glm::vec2 u(0.0f), v(0.0f);
u.x = curr->x - prev->x;
u.y = curr->y - prev->y;
v.x = curr->x - next->x;
v.y = curr->y - next->y;
float CrossProduct = ((u.x * v.y) - (u.y * v.x));
if (CrossProduct < 0)
curr->isConvex = true; // The vertex is convex
else
curr->isConvex = false; // Otherwise concave
float dotProduct = (u.x * v.x) + (u.y * v.y);
curr->Angle =
std::acos(dotProduct /
(std::sqrt(std::pow(u.x, 2.0f) + std::pow(u.y, 2.0f)) *
std::sqrt(std::pow(v.x, 2.0f) + std::pow(v.y, 2.0f))));
curr->Angle = glm::degrees(curr->Angle);
}
|
curr->Angle appears to be set to sin(Angle) from u to v. Therefore concavity/convexity is determined by the sign of ((u.x * v.y) - (u.y * v.x)), since the denominator is always positive.
In particular, if the interior of the polygon is on the right as traversing the vector u from its tail to its head, the positive sign of ((u.x * v.y) - (u.y * v.x)) corresponds to a convex angle.
|
74,469,222
| 74,469,247
|
Returning a child class from a parent class array C++
|
class Component {
// Code here
};
class TransformComponent : public Component {
// Code here
};
class Entity:
public:
Component components[25];
TransformComponent *getTransform() {
for(int i = 0; i < 25; i++) {
if(typeid(components[i]) == typeid(TransformComponent())) {return *(components + i);}
}
}
};
I have an array of components, and inside could be any child class of "Component", like "TransformComponent". The thing is, when compiling, the computer thinks that the components array is only populated with "Component" objects. The function is supposed to return a "TransformComponent", and the compiler sees that as an error, even though the element in the array I am returning is a TransformComponent. Is there any solution to this (preferably simple)?
|
'I have an array of components, and inside could be any child class of "Component", like "TransformComponent".' - this statement is false. If you have an array of Component objects, then at each index in the array, there's exactly a Component-typed object and not a descendant.
If you'd like to store multiple (e.g. Base-Descendants) types, you have two main choices:
use container of (smart) pointers: std::vector<std::unique_ptr<Component>> components
use variants: std::vector<std::variant<Component, TransformComponent/*, ... other types*/> components>;
|
74,469,225
| 74,469,427
|
Is initializer_list considered part of the C++ core language?
|
I ask because auto deduces{} to be initializer_list. I don't know of any other class in the standard library that the core language depends on like this. You could take out vector or array and C++ would still function, but take out initializer_list and it would break.
|
What you call {} (specifically = {...}) the standard calls copy-list-initialization.
And yes, std::initializer_list is given special consideration in the wording of the standard.
If the placeholder-type-specifier is of the form type-constraint auto, the deduced type T replacing T is determined using the rules for template argument deduction. If the initialization is copy-list-initialization, a declaration of std::initializer_list shall precede ([basic.lookup.general]) the placeholder-type-specifier.
[Example 1:
auto x1 = { 1, 2 }; // decltype(x1) is std::initializer_list<int>
auto x2 = { 1, 2.0 }; // error: cannot deduce element type
auto x3{ 1, 2 }; // error: not a single element
auto x4 = { 3 }; // decltype(x4) is std::initializer_list<int>
auto x5{ 3 }; // decltype(x5) is int
|
74,469,734
| 74,469,769
|
How to copy data from base class to derived class fastly?
|
I know move constructor can avoid copy, with a high performance.
but can i use it in copy data from base class to derived class?
for example:
// base.h
class Base {
public:
int a;
char buff[24];
double bp_[10];
};
// derived.h
class Derived : public Base {
public:
int b;
char buff2[16];
};
// main.cpp
int main() {
Base b;
b.a = 1;
snprintf(b.buff, sizeof(b.buff), "helloworld");
b.bp_[0] = 100;
Derived d;
d.b = 9;
snprintf(d.buff2, sizeof(d.buff2), "mytest");
// TODO: how can i move b's data into d with high performance?
}
please see the code, I have a Base object with data, but i want to create a Derived class object, so i need copy data from Base object, is there any good methods like move constructor?
|
There is no general way to do this, as the layout of the data in the base and derived classes may be different. You'll need to write a specific function to do the copying for each class.
One approach would be to write a template function that takes a base class and a derived class, and uses a static_cast to copy the data:
template <typename Base, typename Derived>
void copy_data(Base& b, Derived& d)
{
d = static_cast<Derived>(b);
}
This will work if the layout of the data in the base and derived classes is the same. If it's not, you'll need to write a specific function to do the copying.
|
74,469,822
| 74,469,832
|
What does this program do, and how does it do that?
|
I am having trouble figuring out why this program works. I wrote it based on my notes (OOPP and classes) but I do not understand how exactly it works? I would appreciate any help!
Here is the code:
#include <iomanip>
#include <iostream>
using namespace std;
class Base{
public:
void f(int) {std::cout<<"i";}
};
class Derived:Base{
public:
void f(double){std::cout<<"d";}
};
int main(){
Derived d;
int i=0;
d.f(i);
}
I have tried making cout statements to show me how everything is passed and runs, but it will not allow me to cout anything.
|
This program defines a class called Base, which has a member function called f that takes an int parameter. It also defines a class called Derived, which inherits from Base and has a member function called f that takes a double parameter.
In the main function, an object of type Derived is created, and an int variable is initialized to 0. The member function f is then called on the Derived object, passing in the int variable as a parameter.
When the member function f is called on the Derived object, the compiler looks for a matching function signature in the Derived class. Since there is a function with the same name and parameter list in the Derived class, that function is called. The function in the Derived class prints out a "d", indicating that it was called.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.