question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,632,161 | 69,632,442 | Extremely basic question about namespaces in c++ | using namespace X;
cout << var;
using Y::var;
cout << var;
So say I have a namespace X and a namespace Y that both contain a variable of type int called var. When I say using namespace X; what I imagine happening is if I use some variable that isn't in the global namescope what basically happens is it goes okay I'm gonna look for var in namespace X but now that I also use Y::var what does this exactly mean? Does that just say var is the same as Y::var? But then in that case what's happening with using namespace X does it not even look for var in there because I said I'm using Y::var?
| After the using directive
using namespace X;
the compiler uses the unqualified name lookup to find the name var used in the following statement
cout << var;
And due to the using directive it will find the variable var in the namespace X.
This using declaration
using Y::var;
introduces the variable var from the namespace Y in the current scope and the next statement
cout << var;
will use the variable var from the namespace Y.
Here is a demonstration program.
#include <iostream>
namespace X
{
int var = 1;
}
namespace Y
{
int var = 2;
}
int main()
{
using namespace X;
std::cout << "var = " << var << '\n';
using Y::var;
std::cout << "var = " << var << '\n';
}
The program output is
var = 1
var = 2
That is the using declaration that introduces the variable var in the block scope of the function main hides the declaration of the variable var declared in the namespace X.
In fact the below simplified demonstration program in essence behaves similarly as the above program relative to the name lookup.
#include <iostream>
int var = 1;
int main()
{
std::cout << "var = " << var << '\n';
int var = 2;
std::cout << "var = " << var << '\n';
}
|
69,633,053 | 69,664,316 | How can I convert an existing project with .c and .h files into a dynamic link library in visual studio 2019? | I am using the simple Open EtherCAT Master (SOEM) https://github.com/OpenEtherCATsociety/SOEM. I want to use the existing files in SOEM to create a .dll dynamic link library to build other projects with. I have tried creating a DLL in visual studio and simply uploading all the .c and .h files from SOEM to the DLL. When I do this, some of the header files are not recognized. Specifically the OSAL and OSHW header files. I'm not sure if this is a general issue between the header files or if this is an issue specific to the SOEM files. I would think that once you put all the .c and .h files in the same project, they would all be able to include each other.
| Making the DLL:
put all .c and .h files into dll project
set directories to all files in solution properties > configuration properties > c/c++ > additional include directories
add additional dependecies to libraries for wpcap and others (Ws2_32.lib, wpcap.lib, winmm.lib)
solution properties > configuration properties > linker > input > additional dependecies
set directories for wpcap libraries in solution properties > configuration properties > linker > general > additional library directories
build was successful after step 4
|
69,633,196 | 69,633,269 | lambda iso std::bind for member function | I have the following class on which I run clang-tidy.
template<typename Foo>
class Bar
{
public:
template<class THandlerObj>
Bar(void (THandlerObj::*pCmdHandler)(const Foo&),
THandlerObj* pCmdHandlerContext)
: m_cmdHandlerFunc(std::bind(pCmdHandler, pCmdHandlerContext, std::placeholders::_1))
{
}
private:
std::function<void(const Foo&)> m_cmdHandlerFunc;
}
Clang is telling me that I should use a lambda function instead of std::bind. However I cannot get the syntax straight. I'm struggling with the fact that a member function is given which should be called on the context, but I don't see how to do that.
| You can use lambda's capture list to capture member function pointer and object pointer and invoke them inside the lambda. Try this:
#include <functional>
template<typename Foo>
class Bar
{
public:
template<class THandlerObj>
Bar(void (THandlerObj::*pCmdHandler)(const Foo&),
THandlerObj* pCmdHandlerContext)
: m_cmdHandlerFunc(
[=](const Foo& foo) { (pCmdHandlerContext->*pCmdHandler)(foo); })
{
}
private:
std::function<void(const Foo&)> m_cmdHandlerFunc;
};
If your compiler supports C++20, you can also use std::bind_front which is more lightweight and intuitive than std::bind.
template<class THandlerObj>
Bar(void (THandlerObj::*pCmdHandler)(const Foo&),
THandlerObj* pCmdHandlerContext)
: m_cmdHandlerFunc(std::bind_front(pCmdHandler, pCmdHandlerContext))
{
}
|
69,633,205 | 69,633,400 | libcurl C++: How to correctly install and use on CentOS 7 | Goal:
To correctly install and use libcurl C++ on CentOS 7.
Current output:
When I go to compile a program using libcurl with the command g++ somefile.cpp -lcurl -std=c++11 -o somefile, the following error is received:
[user@localhost ~]$ somefile.cpp -lcurl -std=c++11 -o somefile
somefile.cpp:10:23: fatal error: curl/curl.h: No such file or directory
#include <curl/curl.h>
^
compilation terminated.
Details:
libcurl was installed via sudo yum install libcurl (and also an attempt with sudo yum install libcurl4-openssl-dev). From previous experiences with installing libcurl on Ubuntu 20.04.1 LTS, if I remember correctly I solved a similar issue by setting the LD_LIBRARY_PATH to point to a libcurl.so object as seen below, but this seems to have no effect on CentOS 7.
[user@localhost ~]$ export LD_LIBRARY_PATH=/usr/local/lib/libcurl.so.4
[user@localhost ~]$ sudo ldconfig
If I run the following command I can see the libcurl version which leads me to believe it has been correctly installed:
[user@localhost ~]$ curl --version
curl 7.29.0 (x86_64-redhat-linux-gnu) libcurl/7.29.0 NSS/3.53.1 zlib/1.2.7 libidn/1.28 libssh2/1.8.0
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp scp sftp smtp smtps telnet tftp
Features: AsynchDNS GSS-Negotiate IDN IPv6 Largefile NTLM NTLM_WB SSL libz unix-sockets
Please note: the following resources have been consulted before deciding to ask this question:
https://lynxbee.com/how-to-resolve-fatal-error-curl-curl-h-no-such-file-or-directory-for-ubuntu-linux/
Ubuntu - #include <curl/curl.h> no such file or directory
curl.h no such file or directory
How do I link libcurl to my c++ program in linux?
Summary question:
q1. How can this error be solved when trying to compile a C++ program using libcurl on CentOS 7?
| You will need to install the libcurl-devel package as it contains the headers files you are missing.
The libcurl-devel package includes header files and libraries
necessary for developing programs which use the libcurl library. It
contains the API documentation of the library, too
|
69,633,343 | 69,638,174 | Write Apache Arrow table to string C++ | I'm trying to write an Apache Arrow table to a string. My big example has problems and I can't get this little example to work. This one segfaults inside of Arrow in the WriteTable call. My bigger example doesn't appear to serialize correctly.
#include <arrow/api.h>
#include <arrow/io/memory.h>
#include <arrow/ipc/api.h>
std::shared_ptr<arrow::Table> makeSimpleFakeArrowTable() {
std::vector<std::shared_ptr<arrow::Field>> arrowFields;
arrowFields.emplace_back(std::make_shared<arrow::Field>("Field1", arrow::int64()));
arrowFields.emplace_back(std::make_shared<arrow::Field>("Field2", arrow::float64()));
auto schema = std::make_shared<arrow::Schema>(arrowFields);
std::vector<std::shared_ptr<arrow::Array>> columns(schema->num_fields());
arrow::Int64Builder longBuilder;
longBuilder.Append(20);
longBuilder.Finish(&(columns.at(0)));
arrow::DoubleBuilder doubleBuilder;
doubleBuilder.Append(10.0);
longBuilder.Finish(&(columns.at(1)));
return arrow::Table::Make(schema, columns);
}
std::shared_ptr<arrow::RecordBatch>
getArrowBatchFromBytes(const std::string& bytes) {
arrow::io::BufferReader arrowBufferReader{bytes};
auto streamReader =
arrow::ipc::RecordBatchStreamReader::Open(&arrowBufferReader).ValueOrDie();
auto batch = streamReader->Next().ValueOrDie();
return batch;
}
std::string arrowTableToByteString(const std::shared_ptr<arrow::Table>& table) {
auto stream = arrow::io::BufferOutputStream::Create().ValueOrDie();
auto batchWriter = arrow::ipc::MakeStreamWriter(stream, table->schema()).ValueOrDie();
auto status = batchWriter->WriteTable(*table);
if (not status.ok()) {
throw std::runtime_error(
"Couldn't write Arrow Table to byte string. Arrow status was: '" +
status.ToString() + "'.");
}
std::shared_ptr<arrow::Buffer> buffer = stream->Finish().ValueOrDie();
return buffer->ToHexString();
}
int main(int argc, char** argv) {
auto simpleFakeArrowTable = makeSimpleFakeArrowTable();
std::string tableAsByteString = arrowTableToByteString(simpleFakeArrowTable);
auto batch = getArrowBatchFromBytes(tableAsByteString);
assert(batch != nullptr);
}
| Two things jump to mind. First, I think this is a typo:
longBuilder.Finish(&(columns.at(0)));
arrow::DoubleBuilder doubleBuilder;
doubleBuilder.Append(10.0);
longBuilder.Finish(&(columns.at(1))); // Shouldn't this be doubleBuilder?
Whenever you create an arrow table by yourself it is a good idea to call arrow::Table::ValidateFull. This will help to catch mistakes like this (in this case the status returned would have reported that the input arrays did not match the schema).
Second, if we fix that, we get an error because you return buffer->ToHexString(); which is going to turn your array of bytes into a hex string (e.g. the bytes [10, 20, 30] become the bytes [48, 48, 48, 65, 48, 48, 49, 52, 48, 48, 49, 69], more commonly represented as 000A0014001E).
You then turn around and try to read these hex bytes as a table arrow::io::BufferReader arrowBufferReader{bytes};. If I change that ToHexString to ToString then your example runs and returns 0.
|
69,633,363 | 69,633,373 | How does the linker know where to find a dll file | I am working with Visual Studio and I am trying to get into dlls. I'm wondering how the linker knows where to find a DLL just from the lib file alone.
I specify the lib file and its location in the project settings but where isthe location of the associated dll file specified?
Or maybe i don't understand the topic correctly.
| The Standard Search Order for Desktop Applications from the Microsoft Dll Search Order documentation:
If SafeDllSearchMode is enabled, the search order is as follows:
The directory from which the application loaded.
The system directory. Use the GetSystemDirectory function to get the path of this directory.
The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The current directory.
The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.
If SafeDllSearchMode is disabled, the search order is as follows:
The directory from which the application loaded.
The current directory.
The system directory. Use the GetSystemDirectory function to get the path of this directory.
The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.
|
69,634,096 | 69,636,536 | Configured CMake to compile in C++20 but the executable compiles in C++17 | I am trying to configure CMake to compile my C++ project using the C++20 standard, but it keeps compiling in C++17. My compiler settings in CMakeLists.txt are as follows:
cmake_minimum_required(VERSION 3.21.3 FATAL_ERROR)
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
option(OPTIMISER "Optimiser level 3" OFF)
set(CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 20)
I get the following output when setting up my build directory with CMake:
Configuring CMake files...
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found Python: /usr/bin/python3.9 (found version "3.9.7") found components: Interpreter
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Configuring done
-- Generating done
-- Build files have been written to: /home/niran90/Dropbox/Projects/Apeiron/build
The following is a minimal example in my code that requires C++20 features (requires a constexpr std::fill function):
#include <array>
#include <algorithm>
template <class t_data_type, int array_size>
constexpr auto InitializeStaticArray(const t_data_type& _init_value)
{
std::array<t_data_type, array_size> initialised_array;
std::fill(initialised_array.begin(), initialised_array.end(), _init_value);
return initialised_array;
}
int main()
{
constexpr auto test = InitializeStaticArray<double, 3>(1.0); // This code does not compile.
}
After compiling and running my program, the output that I get for __cplusplus is 201709. Can anyone point out what I might me doing wrong in setting up my CMakeLists.txt?
Additional Outputs:
$ gcc --version
gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
$ cmake --version
cmake version 3.21.3
Edits:
I have just upgraded my gcc and g++ versions to 10.3.0 and I am still unable to compile with C++20.
$ gcc --version
gcc (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0
$ g++ --version
g++ (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0
| So I have managed to compile using C++20 after upgrading to GCC version 11.1.0. Thank you @NicolBolas and @Frank for the insights :)
|
69,634,207 | 69,648,754 | Using mutable for a preallocated working area | I have a C++ class A that can be constructed to perform a certain computation using a function A::compute . This function requires to write to a preallocated memory area (working area) that was allocated at construction of A to perform this computation efficiently. I would like to A::compute to be const in relation to the class, because the computation does not alter the logical state of the object.
Is this a case when the keyword mutable should be used?
Example code:
class A {
public:
A(size_t size) : m_workingArea(size) {}
int compute(const std::vector<int>& data) const {
// ... checks ...
std::copy(data.begin(), data.end(), m_workingArea.begin());
// ... compute ...
// return a result, say first element of the working area
return m_workingArea[0];
}
private:
mutable std::vector<int> m_workingArea;
};
| It is perfectly reasonable to use mutable in this case.
While it is not physically const, the compute(...) method is logically const. That is, to an outside user, compute(...) leaves the object unchanged, despite any internal changes.
Here in the isocpp.org FAQ, the Standard C++ committee recommends that we should prefer logical const over physical const.
Given this, it makes sense to mark m_workingArea mutable, so that compute(...) can be const and logical const-correctness can be maintained. The effect of this should be a clear user interface and clearly stated programmer intent.
|
69,634,466 | 69,634,524 | Why template argument deduction doesn't work in C++? | I have an issue with template arguments deduction in C++.
I don't know why the sample below doesn't work.
The sample:
#include <iostream>
template<size_t n>
void PrintArray(const int arr[n]) {
for (int i = 0; i < n; i++)
printf("%d\n", arr[i]);
}
int main() {
int arr[5] = {1, 2, 3, 3, 5};
PrintArray<>(arr);
return 0;
}
The compiler print this error:
main.cpp: In function 'int main()':
main.cpp:12:21: error: no matching function for call to 'PrintArray(int [5])'
PrintArray<>(arr);
^
main.cpp:4:6: note: candidate: template<unsigned int n> void PrintArray(const int*)
void PrintArray(const int arr[n]) {
^~~~~~~~~~
main.cpp:4:6: note: template argument deduction/substitution failed:
main.cpp:12:21: note: couldn't deduce template parameter 'n'
PrintArray<>(arr);
I've found out that the code becomes working if I pass the argument by reference, so the function signature becomes like this:
void PrintArray(const int (&arr)[n])
But why? Could you please explain me why the compiler can't predict the array size in the first sample, when the array is passed by value?
| This function declaration
void PrintArray(const int arr[n]) {
is equivalent to
void PrintArray(const int *arr) {
due to adjusting by the compiler the parameter having an array type to pointer to the array element type.
From the C++ 14 Standard (8.3.5 Functions)
5 A single name can be used for several different functions in a
single scope; this is function overloading (Clause 13). All
declarations for a function shall agree exactly in both the return
type and the parametertype-list. The type of a function is determined
using the following rules. The type of each parameter (including
function parameter packs) is determined from its own
decl-specifier-seq and declarator. After determining the type of
each parameter, any parameter of type “array of T” or “function
returning T” is adjusted to be “pointer to T” or “pointer to function
returning T,” respectively. After producing the list of parameter
types, any top-level cv-qualifiers modifying a parameter type are
deleted when forming the function type. The resulting list of
transformed parameter types and the presence or absence of the
ellipsis or a function parameter pack is the function’s
parameter-type-list. [ Note: This transformation does not affect the
types of the parameters. For example, int()(const int p,
decltype(p)) and int()(int, const int) are identical types. — end
note ]
So it is impossible to deduce the template parameter n.
Declare the function like
void PrintArray(const int ( &arr )[n]) {
Or you could call your original function by specifying explicitly the template argument like
PrintArray<5>(arr);
|
69,634,555 | 69,635,110 | GMock std::any argument | I have an interface
class IUObject {
public:
virtual void setProperty(const std::string& name, const std::any& value) = 0;
virtual void setProperty(const std::string& name, std::any&& value) = 0;
};
I`ve created mock object:
class MockUObject : public IUObject {
public:
MOCK_METHOD(void, setProperty, (const std::string& name, const std::any& value), (override));
MOCK_METHOD(void, setProperty, (const std::string& name, std::any&& value), (override));
};
I need to test setProperty function via EXPECT_CALL.
I`ve tried something like this:
MockUObject *mock = new MockUObject();
/// Some code here
EXPECT_CALL(*mock, setProperty(TypedEq<const std::string&>("position"),
TypedEq<std::any&&>(std::any(std::pair<double, double>(6.0, 2.0)))));
But compiler cant compare std::any:
error: no match for 'operator==' (operand types are 'const std::any' and 'const std::any')
I cant change base interface functions, so i have to work with std::any. How can i deal with this problem?
| AFAIK, there is no matcher for std::any, so you need to write your own.
MATCHER_P(AnyMatcher, value, "")
{
// assume the type of parameter is the same as type stored in std::any,
// will not work e.g. when any stores std::string and you pass a literal
// you'd need to write a template matcher for that case
return std::any_cast<decltype(value)>(arg) == value;
}
Usage:
EXPECT_CALL(*mock, setProperty(TypedEq<const std::string&>("position"),
AnyMatcher(std::pair<double, double>(6.0, 2.0))));
See it online (and a passing case). Note that you cannot really have overloads where one function has const lvalue reference as argument and the other rvalue reference, because that's ambiguous (both can accept rvalue as argument).
|
69,634,598 | 69,634,882 | std::vector of std::array of different sizes | As an exercise, I would like to construct a vector containing std::array<unsigned char, N> objects (where N varies).
My attempt was to construct a base class GenericArray from which a MyArray<N> will derive, such that the container will actually be: std::vector<GenericArray*>. However, since the actual array variable must reside in the derived class, I do not see a way to make use of this data from the std:vector<GenericArray*> itself.
Here is my full attempt, which obviously produces: error: ‘class GenericArray’ has no member named ‘data’
#include <array>
#include <cassert>
#include <iostream>
#include <vector>
template<std::size_t N>
using arr_t = std::array<unsigned char, N>;
class GenericArray
{
public:
~GenericArray() = default;
};
template<std::size_t N>
class MyArray : public GenericArray
{
public:
arr_t<N> data;
MyArray(const arr_t<N>& data)
{
this->data = data;
}
};
int main(void)
{
std::vector<GenericArray*> vs;
vs.emplace_back(new MyArray<2>({ 'a', 'b' }));
vs.emplace_back(new MyArray<4>({ 'A', 'B', 'C', 'D' }));
assert(vs.size() == 2);
for (const auto& x : vs[0]->data)
{
std::cout << x << "\n";
}
return 0;
}
| You seem to be mixing two concepts. I recommend the version in eerorika's answer but if you really want base class pointers in your container, here's one way:
#include <array>
#include <iostream>
#include <vector>
#include <memory>
class GenericArray {
public:
using value_type = unsigned char;
using iterator = value_type*;
template<std::size_t N>
using arr_t = std::array<value_type, N>;
virtual ~GenericArray() = default; // must be virtual to call the derived dtor
virtual iterator begin() = 0; // used for iterating in the derived class
virtual iterator end() = 0;
// add `const` versions too as needed
};
template<std::size_t N>
class MyArray : public GenericArray {
public:
arr_t<N> data;
MyArray(const arr_t<N>& data) : data(data) {}
iterator begin() override { return data.data(); } // overridden
iterator end() override { return data.data() + data.size(); } // -"-
};
int main() { // no need for main(void)
std::vector<std::unique_ptr<GenericArray>> vs;
vs.emplace_back(new MyArray<2>({ 'a', 'b' }));
vs.emplace_back(new MyArray<4>({ 'A', 'B', 'C', 'D' }));
// loop over the elements:
for(auto& ptr : vs) {
for(auto& x : *ptr) std::cout << x << ' ';
std::cout << '\n';
}
}```
|
69,635,212 | 69,635,422 | What's the time-complexity function [ T(n) ] for these loops? | j = n;
while (j>=1) {
i = j;
while (i <= n) { cout<<"Printed"; i*= 2; }
j /= 2;
}
My goal is finding T(n) (function that gives us number of algorithm execution) whose order is expected to be n.log(n) but I need exact function which can work fine at least for n=1 to n=10 data
I have tried to predict the function, finally I ended in *T(n) = floor((n-1)log(n)) + n
which is correct just for n=1 and n=2.
I should mention that I found that inaccurate function by converting the original code to the for-loop just like below :
for ( j = 1 ; j <= n ; j*= 2) {
for ( i = j ; i<= n ; i*=2 ) {
cout << "Printed";
}
}
Finally I appreciate your help to find the exact T(n) in advance.
| using log(x) is the floor of log based 2
1.)
The inner loop is executed 1+log(N)-log(j) the outer loop executed times 1+log(N) with j=1,2,4...N times the overall complexity is T(N)=log(N)log(N)+2*log(N)+1-(log(1)+log(2)+log(4)...+log(N))= log(N)^2-(0+1+2+...+log(N))+2*log(N)+1= log(N)^2-log(N)(log(N)-1)/2+1= log(N)^2/2+3*log(N)/2+1
2.) same here just in reverse order.
I know it is no proof but maybe easier to follow then math : godbolt play with n. it always returns 0;
|
69,635,343 | 69,640,909 | Is there a way to save CGAL::Linear_cell_complex_for_combinatorial_map as .off or .obj format? | I have just implemented an algorithm that takes a surface mesh, tetrahedralizes it and saves the tetrahedralization data inside the CGAL data structure CGAL::Linear_cell_complex_for_combinatorial_map.
I'm new to using CGAL library and I would like to know if there is a way to write CGAL::Linear_cell_complex_for_combinatorial_map data structure in .obj, .off or some other formats.
| There is an undocumented function write_off(lcc) (cf here).
In the off, when a face is shared by two volumes, the face is saved twice. Moreover, the output mesh is not a surface, and some tools (like meshlab) does not like such a mesh.
It is easy to modify the code of write_off to save only the surface of your volumic mesh. Contact me if you need such function.
|
69,635,557 | 69,636,001 | Conversion between types: C++ to C++/CLI | I am trying to wrap a C++ library into a C++/CLI library for use in C#. I am having trouble with conversion between types...
The C++ function looks like this (this is from MyCppLib.h file, I can't change the C++ code):
int CppFunc(void* Handle, wchar_t* Feature, long long* Value)
My C++/CLI wrapper function looks like:
#include "MyCppLib.h"
#include <msclr\marshal.h>
#include <string.h>
#include <stdlib.h>
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace msclr::interop;
namespace MyCppCliLib
{
int CppCliFunc(IntPtr Handle, String^ Feature, long long* Value) {
return ::CppFunc(Handle.ToPointer(), string_to_wchar(Feature), Value);
}
static wchar_t* string_to_wchar(String^ managedString)
{
marshal_context^ context = gcnew marshal_context();
wchar_t* unmanagedString = context -> marshal_as<wchar_t*>(managedString);
delete context;
return unmanagedString;
}
}
However, it seems I can't Marshall the String^ to wchar_t*... there is error C2065 saying "this conversion is not supported". Although if I replace it with const wchar_t*, it seems to work... I don't get it... And I am not sure if I am converting Handle and Value types correctly...
How can I convert C++ void*, wchar_t* and long long* types to C++/CLI ?
| The marshal_context class is a native type, not a garbage-collected type. So you cannot write gcnew marshal_context()
The intended use is as follows:
marshal_context context;
const wchar_t* unmanagedString = context.marshal_as<const wchar_t*>(managedString);
// use unmanagedString
// when context goes out of scope, both the context object and the memory for unmanagedString are freed
You have a problem though, you want to return a pointer. Nothing in your question or code has said anything about the contract between string_to_wchar and its caller about how the memory should be eventually freed. We can avoid this problem by noting that your helper function has gotten too short to be useful, so you can eliminate it:
#include <msclr\marshal.h>
int CppCliFunc(IntPtr Handle, String^ Feature, long long* Value)
{
marshal_context context;
return ::CppFunc(Handle.ToPointer(),
context.marshal_as<const wchar*>(Feature),
Value);
}
Now the string data is still alive at the time that ::CppFunc needs it.
However, you need a non-const pointer. System::String^ is meant to be immutable (it isn't actually, which causes some problems) and so the marshal_as library prevents you from getting a writable pointer. You can easily get a writable pointer to a copy of the string, though:
#include <msclr\marshal_cppstd.h>
int CppCliFunc(IntPtr Handle, String^ Feature, long long* Value)
{
std::wstring strFeature{marshal_as<std::wstring>(Feature)};
return ::CppFunc(Handle.ToPointer(),
&stdFeature[0],
Value);
}
|
69,635,623 | 69,635,687 | Deleting dynamic array in C++ causes an error | I have a class called Myclass. In the main function, I have created an array object for this class. Whenever I try to delete this dynamically allocated array, the visual studio will say, Error: Debug Assertion Failed!. Expression: is_block_type_valid(header->_block_use). Can you please tell me what is causing this or show me an example of fixing this issue.
#include <iostream>
using namespace std;
class Myclass
{
public:
void print()
{
cout << "Hello from Myclass" << endl;
}
};
int main()
{
Myclass *obj[3] = { new Myclass, new Myclass, new Myclass };
// Call each object's print function.
for (int index=0; index < 3; index++)
{
obj[index]->print();
}
delete[] obj; //Error
return 0;
}
| This:
Myclass *obj[3] = { new Myclass, new Myclass, new Myclass };
is not a dynamically allocated array. It is an array with automatic storage, holding pointers to dynamically allocated objects. To properly clean up, you need:
delete obj[0];
delete obj[1];
delete obj[2];
Because every new must be matched with a delete, and you can only delete via delete[] something that was allocated via new[].
There is no need for any dynamic allocation here, just do:
Myclass obj[3] = {};
|
69,636,257 | 69,636,937 | C++ Linked List Insert Implementation | Disclaimer: I am somewhat new to coding, and this is a pretty simple question, but I can't quite find the answer anywhere else, so I decided to ask my first question here, I hope it hasn't been asked already(if it has, I haven't found it). I hope this is an appropriate forum for my question.
I'm trying to create a linked list for a course I'm taking. I'm struggling with inserting a new value at the end of the list. Here is my add/insert method, which I basically stole from my textbook, but I'm confused about:
class Node {
public:
int elem = 0;
Node* next = NULL;
}; // I'm including the Node class in this question for reference
//Here's the method that confuses me
void SList::Insert(int key) { // add to front of list
Node* v = new Node; // create new node
v−>elem = e; // store data
v−>next = head; // head now follows v
head = v; // v is now the head
}
I guess my question is this: when the add method runs, it creates a new node, v, whenever it is called (at least, that's how I understand it). If the method is called multiple times, doesn't this create multiple instances of the node class with the same name (v), which should cause an error?
The code does work as intended, but I'm hoping somebody can take a second to explain to me why it works. I'm not super familiar with C++, I'm much more familiar with java, so I'm guessing there's just some aspect of C++ I don't understand.
| First things first, this code snippet is inserting a new node at the beginning of our linked list (which is identified by the head pointer) and not at the end. v is a temporary identifier to hold our new node which is not attached to our list yet.
Let's say our list looks like this initially:
[head] -> [1,n2] -> [2,n3] -> [4,NULL].
(head is only a node pointer, not a node)
After this statement v−>elem = e; we have our new node as : [v] -> [e,NULL]
v−>next = head; : this line doesn't mean head follows v, it just means we are setting our new node to point to the same node where head is pointing to. So now our list will look like this:
[v] -> [e,n2] -> [1,n2] -> [2,n3] -> [4,NULL]
Note: [head] is still pointing to our second node [1,n2], which should now be pointing towards our first newly created node, which is achieved by our last line head = v;. v now goes out of scope and our list looks like this :
[head] -> [e,n2] -> [1,n2] -> [2,n3] -> [4,NULL]
|
69,636,423 | 69,636,472 | Functor or boolean comparator | What should I use? bool compare or sCompare() functor? And why?
Are there some differences between using this two options?
struct Dog
{
int m_age{};
int m_weigt{};
};
bool compare(const Dog& a, const Dog& b)
{
return a.m_age > b.m_age;
}
struct sCompare
{
bool operator()(const Dog& a, const Dog& b)
{
return a.m_age > b.m_age;
}
};
int main()
{
vector<Dog> dogs{ Dog{1,20}, Dog{2,10}, Dog{3,5}, Dog{10,40} };
//sort(begin(dogs), end(dogs), compare); this
//sort(begin(dogs), end(dogs), sCompare()); or this
return 0;
}
| Your two comparators result in opposite ordering (< vs >). Other than that the biggest difference is that you cannot define a function within a function, but you can define a type in a function. Moreover, lambda expressions offer straightforward syntax to do that:
int main()
{
vector<Dog> dogs{ Dog{1,20}, Dog{2,10}, Dog{3,5}, Dog{10,40} };
sort(begin(dogs), end(dogs), [](const Dog& a,const Dog& b){ return a.m_age < b.m_age;});
// or
auto comp = [](const Dog& a,const Dog& b){ return a.m_age < b.m_age;}
sort(begin(dogs), end(dogs),comp);
}
|
69,636,479 | 69,647,357 | QTimer::singleShot(..) inside connect(..) function | I want to update the background of my game after 10 seconds. I used singleShot function of QTimer inside the connect function. It does work correctly for the first time but after the first call, update background function is being called after every 1 second (or so). I am new to Qt, please excuse my ignorance.
Here is the relevant code :
void Scene::setUpPillarTimer(QGraphicsPixmapItem* pixItem)
{
QTimer *backgroundTimer = new QTimer();
int durationOfPillar = 0;
pillarTimer = new QTimer(this);
connect(pillarTimer, &QTimer::timeout,this, [=]()mutable{
PillarItem *pillarItem = new PillarItem(durationOfPillar);
addItem(pillarItem);
backgroundTimer->singleShot(10000, this, [=](){
updateBackground(pixItem);
});
});
pillarTimer->start(800);
}
| So I removed the singleShot function and inserted simple connect function with a timeout 100000 ms.
void Scene::setUpPillarTimer(QGraphicsPixmapItem* pixItem)
{
QTimer *backgroundTimer = new QTimer(this);
int durationOfPillar = 0;
connect(backgroundTimer, &QTimer::timeout, this, [=](){
updateBackground(pixItem);
});
backgroundTimer->start(10000);
pillarTimer = new QTimer(this);
connect(pillarTimer, &QTimer::timeout,this, [=]()mutable{
PillarItem *pillarItem = new PillarItem(durationOfPillar);
addItem(pillarItem);
});
pillarTimer->start(800);
}
|
69,636,506 | 69,667,646 | Rationale behind the usual implemention of std::swap overloads | Let's consider the following minimal code sample:
// Dummy struct
struct S
{
int a;
char * b;
// Ctors, etc...
};
void swap(S & lhs, S & rhs)
{
using std::swap;
swap(lhs.a, rhs.a);
swap(lhs.b, rhs.b);
}
Context
I know that when we intend to call a swap() function, the proper and recommended way to proceed is to do as follows:
// Let's assume we want to swap two S instances.
using std::swap;
swap(s1, s2);
This way, ADL is able to find the proper overload if any (defined in the given type namespace), otherwise std::swap is used.
Then I read some SO threads:
How to overload std::swap()
Is specializing std::swap deprecated now that we have move semantics?
Move semantics == custom swap function obsolete?
And some others
where the same idiom is used (even for built-in or pointer types), but not only when we call the std::swap() overload but also when we define it.
Question
If the members are all built-in types (or pointer types, possibly pointers to custom types), is it still necessary/recommended to use that idiom instead of explicitly calling std::swap() ?
For example, considering the small code sample I provided, since S members are built-in types, is it fine (well-formed) to define it as below instead:
void swap(S & lhs, S & rhs)
{
std::swap(lhs.a, rhs.a);
std::swap(lhs.b, rhs.b);
}
Or maybe is there a reason I couldn't see that would still require to use the using std::swap; way ?
|
since S members are built-in types, is it fine (well-formed) to define it as below instead: [std::swap usage]
Yes. I mean, it works because std::swap just "swaps the values a and b" if they are both MoveAssignable and MoveConstructible, which built-in types are.
If the members are all built-in types (or pointer types, possibly pointers to custom types), is it still necessary/recommended to use that idiom instead of explicitly calling std::swap() ?
Just for the future of your class: if one day any of its members gets replaced with a user-defined type, you might forget to modify your swap and miss a "specialized" ADL implementation for it, still calling the generic std::swap which could (theoretically) be inefficient yet still compile.
Actually, you don't even need to think about it if you just always use boost::swap or implement it yourself:
template<typename T> void swap(T& a, T& b) {
using std::swap;
swap(a, b);
}
|
69,636,547 | 69,637,173 | C(++): Replace function declaration with macros but not its invocations | I have a library I can't change where some function is declared, implemented and used, in single file. Lots of other stuff is done in that same file. I want to override that single function to do another thing. The issue is that when I use renaming macro, all the places where that macro/function name is found are replaced, both declarations and invocations. I want some way to rename only declaration or invocations. Then I'll be able to simply drop-in my own function under initial name as a replacement.
The code looks like this:
// library-module.cpp
int foo(int a, int b) // declaration
{
return a+b;
}
int bar()
{
return foo(1, 2); // invocation
}
// main.cpp
// MAGIC HAPPENS HERE
#include "library-module.cpp"
int foo(int a, int b) // drop-in replacement
{
return a-b;
}
int main()
{
return bar(); // should be -1, not 3
}
Another option would be to do a vice-versa operation: to replace all invocations to some other symbol, but not the declaration. Though it's not preferred, because there might be other users of that function name in the wild.
Yet another option would be to do it in runtime, but I believe it's not that great.
Thank you.
UPD1:
It's c++.
Here are the actual function declaration, implementation and usage in the file.
What I wanted is to substitute a single line of the function set_scenario, not touching anything else, from my other app that uses all that app's code. The idea was to keep the maintenance of all the code, except that very function, to the core team, and to handle this one myself, because i need some specific implementation. Thus I am including not the headers, but the implementation, and want such a dirty hack. Maybe I'm on the wrong way?
In the end I've made a fork, changed the line and settled with this, though I believe it would've been better if I didn't do a fork, because it becomes way harder to get the changes.
Another thought that comes to my mind is possibly I've to make a patch for the function I'm to change and apply it on every build. This way it would be precisely known what was that single line that changed, and I would immediately know that the initial function changed if I had patch applying error. Maybe this is a better way of achieving the same thing?
And in the end, it was very interesting for me do deal with that using macros, because it's rather black magic to me.
Thank you again.
| It may or may not be possible depending on how exactly the function is defined and used.
Assuming the exact declaration and usage you've shown, you can do this:
#define foo(a, b) FOO_LOW(CAT(DETECT_, a) CAT(DETECT_, b))(a, b)
#define CAT(a, b) CAT_(a, b)
#define CAT_(a, b) a##b
#define DETECT_int ,
#define FOO_LOW(...) FOO_LOW_(__VA_ARGS__)
#define FOO_LOW_(a, ...) CAT(FOO_IMPL, __VA_OPT__(_DECL))
#define FOO_IMPL(a, b) replacement(a, b)
#define FOO_IMPL_DECL(a, b) foo(a, b)
constexpr int foo(int a, int b) {return a + b;}
constexpr int replacement(int a, int b) {return a - b;}
static_assert(foo(100, 10) == 90);
This implementation requires C++20, and additionally MSVC needs /Zc:preprocessor and Clang (13 and earlier, see bug) needs -Wno-gnu-zero-variadic-macro-arguments. It's possible to implement with an earlier standard and without those flags, but the macro will be more convoluted.
This specific implementation has some limitations:
It checks if both arguments start with int, so if it happens in a function call, it will be incorrectly considered a declaration, e.g. foo(int(1), int(2)).
If an argument contains a , outside of ( ), you get a compilation error, e.g. foo(std::array{1,2}[0], 1).
If an argument begins with a punctuation, you get a compilation error, e.g. foo((1), (2)).
|
69,636,593 | 69,658,895 | Predefined C++ Types (compiler internal) Not Found error | I'm attempting to write a game of tic tac toe just for fun and am running into this error when I try to debug the application. The error occurs on line 23, the multidimensional std::array declaration. I can't find any material on the subject or come up with my own solution. The error shows up in a "Source not found" tab in VS 2019, doesn't look like a normal error, and this is the text: "predefined C++ types (compiler internal) not found
You need to find predefined C++ types (compiler internal) to view the source for the current call stack frame."
#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <algorithm>
#include <array>
#include <string>
class tic_tac_toe
{
private:
enum class values
{
X,
O,
max_values
};
struct square_data
{
std::string code{};
values value{};
};
std::array<std::array <square_data, 3>, 3> board{};
public:
tic_tac_toe()
{
for (int a{ 0 }; a < 3; ++a)
{
for (int b{ 0 }; b < 3; ++b) {
switch (a)
{
case 0:
board.at(a).at(b).code = "A";
board.at(a).at(b).value = values::max_values;
break;
case 1:
board.at(a).at(b).code = "B";
board.at(a).at(b).value = values::max_values;
break;
case 2:
board.at(a).at(b).code = "C";
board.at(a).at(b).value = values::max_values;
break;
default:
std::cout << "initializer failed\n"; //shouldn't happen
}
board.at(a).at(b).code.append(std::to_string((b + 1)));
}
}
print_grid();
}
void print_code(square_data square)
{
switch (square.value)
{
case values::X:
std::wcout << L"X";
break;
case values::O:
std::wcout << L"O";
break;
default:
std::wcout << L" ";
}
}
void print_grid()
{
fflush(stdout);
int previous{ _setmode(_fileno(stdout), _O_U16TEXT) }; //print unicode
for (int a{ 0 }; a < 3; ++a)
{
switch (a)
{
case 0:
std::wcout << L"\n┌───┬───┬───┐\n│ ";
break;
case 1:
std::wcout << L"\n├───┼───┼───┤\n│ ";
break;
case 2:
std::wcout << L"\n├───┼───┼───┤\n│ ";
break;
default:
std::cout << "printer failed\n";
}
for (int b{ 0 }; b < 3; ++b) {
print_code(board.at(a).at(b));
std::wcout << L" │ ";
}
}
std::wcout << L"\n└───┴───┴───┘\n";
fflush(stdout);
_setmode(_fileno(stdout), previous); //for switching back to narrow output
}
};
int main()
{
tic_tac_toe game{};
return 0;
}
| This is an error of VS. It works when I remove /permissive-. This problem has already been reported.
|
69,637,120 | 69,637,163 | How to avoid copy/memory overhead when wrapping a stack allocated object? | Let's say I have a large blob object that is stack allocated. I need to put that in a wrapper object but I want to avoid a copy. Should I just use std::move with a move constructor? What would be the easiest way to prove that it works?
struct Blob {
char blob[1024 * 1024]; // imagine something big here
};
template <typename T>
struct Foo {
Foo(T&& src) : data{src} {}
T data;
};
int main() {
Blob blob;
Foo foo{std::move(blob)}; // do not copy
// should not take twice the memory of a blob
}
| In this case, Blob is plain old data. The compiler is free to optimize the variable Blob blob out of existence.
It is also free to make a million copies of it for no reason whatsoever. The standard does not constrain it.
There is an optimization called "static single assignment" that represents local object states as independent existence variables, which allows the compiler to get rid of a pile of nonsense copies or other state changes that don't matter. Sufficiently complex code, or reference/pointer leaks outside of the scope of optimization, block it.
So, in practice, just don't block the compiler from optimizing Blob blob's existence away.
That being said
Foo(T&& src) : data{src} {}
this should read
Foo(T&& src) : data{std::forward<T>(src)} {}
Also, you could do a
Foo<Blob&> foo(blob);
and have Foo store a reference to the Blob data. This changes the "value semantics" of Foo in nasty ways however.
Note that your implicit deduction guide is equally crazy, in that if you pass an lvalue you'll get a Foo wrapping a reference, but if you pass an rvalue you get a Foo wrapping a value.
If you want a hard guarantee, C++ doesn't provide that. C++ doesn't even guarantee that Blob blob; actually takes up space on the stack.
Going further, you can do this:
int main() {
Foo foo{[&]{
Blob blob;
return blob;
}()};
}
in this case, Blob blob's existence is elided into the return value, which in turn is passed to foo, then the lifetime of the return value ends at th end of the full-expression. Instead of a lambda, you can also use another function outside of main.
This makes it a bit easier for the compiler to work out that there is no point in a separate Blob object, but not be a huge amount.
If you want to make elision of the Blob blob directly into the Foo data be more guaranteed, add a Foo constructor that takes a Blob factory:
template <typename T>
struct Foo {
template<class U>
requires std::is_same_v< std::decay_t<U>, T >
Foo(U&& src) : data{std::forward<U>(src)} {}
template<class F>
requires std::is_invocable_r_v< T, F&& >
Foo(F&& f) : data(std::forward<F>(f)()) {}
T data;
};
template<class T>
requires !std::is_invocable_v< T&& >
Foo(T&&)->Foo<std::decay_t<T>>;
template<class F>
requires std::is_invocable_v< F&& >
Foo(F&&)->Foo<std::decay_t<std::invoke_result_t<F&&>>>;
int main() {
Foo foo{[&]{
Blob blob;
return blob;
}};
}
which is probably going way, way too far.
|
69,637,186 | 69,637,277 | Cast pointer of the base class to pointer of the inherited class with template | My code looks something like this:
class A {
...
};
template<typename T>
class B: public A {
...
};
A* pointerA = new B<X>(...);
But now I want to cast another pointerB to pointerA:
B<...>* pointerB = (B<...>*)pointerA;
How do I know what to insert into <...> or how I should do this correctly?
| You can try the cast with dynamic_cast. If you dynamic_cast to a pointer type and it fails, you get a null pointer back. If you dynamic_cast to a reference type and it fails, you'll get an exception.
Example:
#include <iostream>
class A {
public:
virtual ~A() = default;
};
template<typename T>
class B : public A {};
int main() {
A* pointerA = new B<int>;
auto pointerB = dynamic_cast<B<double>*>(pointerA);
if(pointerB) {
std::cout << "cast succeeded\n";
} else {
std::cout << "cast failed\n"; // will print "cast failed"
}
delete pointerA;
}
If you have many of them stored in a vector you need to test all possible types to be able to cast back to the original type.
Example:
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class A {
public:
virtual ~A() = default;
};
template<typename T>
class B : public A {};
int main() {
std::vector<std::unique_ptr<A>> vec;
vec.emplace_back(new B<int>);
vec.emplace_back(new B<std::string>);
for(auto& ptr : vec) {
if(auto b = dynamic_cast<B<int>*>(ptr.get())) {
std::cout << "B<int>\n";
} else if(auto b = dynamic_cast<B<std::string>*>(ptr.get())) {
std::cout << "B<std::string>\n";
} else {
std::cout << "Oh, unknown derived type stored ...\n";
}
}
}
It's preferable to add virtual methods to the base class and implement them in the derived classes to not have to do this cast at all though.
|
69,637,240 | 69,765,184 | "ferror" tests "scanf" input | I tried to enter error data in next program but it can't recognize the error. Once I entered numeric data, and next time entered string data but the program made no reaction:
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main(void)
{
int i;
scanf("%d",&i);
if(ferror(stdin))
printf("Error is ocurred!");
}
| Don't assume what a function does. Read it's documentation.
https://www.cplusplus.com/reference/cstdio/ferror/
int ferror ( FILE * stream );
Check error indicator
Checks if the error indicator associated with stream is set, returning a value different from zero if it is.
This indicator is generally set by a previous operation on the stream that failed, and is cleared by a call to clearerr, rewind or freopen.
So this depends on if scanf has set the error indicator, which it does not in this situation.
Instead, use this:
if(scanf("%d",&i) != 1) {
// Error code
Oh, and don't use use namespace std Why is "using namespace std;" considered bad practice?
|
69,638,177 | 69,638,363 | How do you block shared memory access until it is ready? | I'm trying to share a mutex between several processes. Each process will begin running at some random time so I need each to to be capable of setting up the shared memory and getting the mutex ready for usage. This works great so far:
int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR);
if (fd < 0) {
fd = shm_open(name, O_RDWR, S_IRUSR);
} else {
//**critical section**
// set up the mutex inside the shared memory
// update permissions so other processes can access the shared memory
fchmod(fd, S_IRUSR | S_IWUSR)
//**critical section**
}
// mmap() shared memory
// pthread_mutex_lock()
// some other critical section
// pthread mutex unlock()
but if I add a sleep() right at the start of the else block to simulate slow creation of the shared memory I run into a problem where another process will see the created file and try to use it right away, before it's ready.
Is there any way to block the shm_open() call until the shared memory is ready? like telling it to wait until it has sufficient permissions to open the file (the last step of my critical section). Or is there some way to lock the file immediately on creation so that other processes must wait for it to be set up and unlocked, flock()?
| I've actually solved my own question here, anyone have any suggestions for improvements?
Solution:
int lock_fd shm_open(setup_control, O_RDWR | O_CREAT, S_IRUSR, S_IWUSR);
flock(lock_fd, LOCK_EX);
int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR, S_IWUSR);
if (fd < 0) {
fd = shm_open(name, O_RDWR, S_IRUSR);
} else {
//**critical section**
// set up the mutex inside the shared memory
//**critical section**
}
flock(lock_fd, LOCK_UN);
// mmap() shared memory
// pthread_mutex_lock()
// some other critical section
// pthread mutex unlock()
Basically the locking file ensures that only 1 process can be acquiring or setting up the mutex at once which means by the time [the next] process is opening the mutex file it has already completed setting up
|
69,638,421 | 69,638,546 | Conway's game of life algoritm is not working | I'm trying to simulate conway's game of life. The algorithm I made is not working, but I can't figure out how.
If I have a situation like this:
|.........|
|....x....|
|....x....|
|....x....|
|.........|
a . is a dead cell, an x is an alive cell
It is expected that the vertical bar flips into a horizontal bar, but this doesn't happen.
Instead it only removes the bottom one, running it again again only removes the bottom so theres 1 left.
Clearly theres something wrong with the algorithm, but I can't figure out what.
I've been looking online but all problems other people have had, the solutions didn't work for me.
So what is the error in this algorithm?
This is my code:
void new_generation() {
// Create one new generation
// double for loop -> iterates every cell
for (int i=0; i<worldHeight; i++){
for (int j=0; j<WorldWidth; j++) {
// find the amount of living neighbours, stored in count
// dubbele for loop -> iterates every neighbour of the current cell
count = 0;
for (int y=0; y<2; y++) {
for (int x=0; x<2; x++){
if (i != 0 and j!= 0) { // the cell itself doesnt count
if (world[i+y][j+x]) count++;
}
}
}
if (world[i][j]) { // current cell is alive
if (count<2 or count>3) new_world[i][j] = false;
else new_world[i][j] = true;
}
else { // current cell is dead
if (count==3) new_world[i][j] = true;
else new_world[i][j] = false;
}
}
}
// copy every value from the newly generated world to the current
// double foor loop -> iterates every cell
for (int i=0; i<worldHeight; i++){
for (int j=0; j<WorldWidth; j++) {
world[i][j] = new_world[i][j];
}
}
worldHeight and worldWidth are ints denoting how big the world is.
world and new_world are 2-dimensional arrays containing booleans where true is a living cell and false is a dead cell
| You count the neighbor cells wrong
Both x and y are runing from 0 to 2 not from -1 to 2. in
for (int y=0; y<2; y++) {//should be int y=-1; y<2; y++
for (int x=0; x<2; x++){//should be int x=-1; x<2; x++
if (i != 0 and j!= 0) { // shold be x!=0 or y!=0
if (world[i+y][j+x]) count++;
}
}
}
Also you have to check if world[i+y][j+x] is valid (coordinates are in teh 0,size range)
And the third problem is that when you want not to count in word[i][j] you check if (i!=0 and j!=0) not x!=0 or y!=0 i and j are the coordinates of the examined cell, x and y are the difference of the coordinates.
|
69,638,521 | 69,644,144 | C++ multithreaded access of boolean member | Due to low latency requirement, I'm using parallel execution of for_each to recognize intention of a sentence (a set of strings). I learnt before that there is no need for mutex to protect bool or any data type that its size is less than one byte. So I'm asking if accessing boolean member Tag.m_Found is thread safe? Otherwise, should I use atomic or mutex?
#include <iostream>
#include <unordered_set>
#include <set>
#include <list>
#include <algorithm>
#include <execution>
struct Tag{
const std::unordered_set<std::string> m_Context;
const std::string m_Name;
volatile bool m_Found;
Tag(const std::unordered_set<std::string> context, const std::string name)
: m_Context(context)
, m_Name(name)
, m_Found(false)
{}
Tag(const Tag & tag) = delete;
Tag(Tag && tag) = default;
Tag & operator=(const Tag & tag) = delete;
};
int main(){
const std::set<std::string> input = {"hello", "my", "son"};
std::list<Tag> intentions;
intentions.emplace_back(Tag({"hello", "Hi", "morning"}, "greeting"));
intentions.emplace_back(Tag({"father", "mother", "son"}, "family"));
intentions.emplace_back(Tag({"car", "bus", "airplan"}, "transportation"));
for_each( std::execution::par
, std::begin(input)
, std::end(input)
, [& intentions](const std::string & input_element)
{
for_each( std::execution::par
, std::begin(intentions)
, std::end(intentions)
, [& input_element](Tag & intention){
if(!intention.m_Found){
intention.m_Found = intention.m_Context.find(input_element)!=intention.m_Context.end();
}
}
);
}
);
for_each( std::execution::seq
, std::begin(intentions)
, std::end(intentions)
, [](Tag & intention){
if(intention.m_Found){
std::cout<<intention.m_Name;
}
}
);
return 0;
}
| The issue is if adding "std::mutex m_Found_access;" or making "atomic_bool m_Found;" the default move constructor is deleted so I need to define a move constructor for Tag. And m_Found should only be set to true to avoid race condition (as @Nate Eldredge mentioned). The code becomes:
#include <iostream>
#include <unordered_set>
#include <set>
#include <list>
#include <algorithm>
#include <execution>
struct Tag{
const std::unordered_set<std::string> m_Context;
const std::string m_Name;
std::atomic_bool m_Found;
Tag(const std::unordered_set<std::string> context, const std::string name)
: m_Context(context)
, m_Name(name)
, m_Found(false)
{}
Tag(const Tag & tag) = delete;
Tag & operator=(const Tag & tag) = delete;
Tag(Tag && tag) : m_Context(std::move(tag.m_Context))
, m_Name(std::move(tag.m_Name))
, m_Found(static_cast< bool >(tag.m_Found))
{}
};
int main(){
const std::set<std::string> input = {"hello", "my", "son"};
std::list<Tag> intentions;
intentions.emplace_back(Tag({"hello", "Hi", "morning"}, "greeting"));
intentions.emplace_back(Tag({"father", "mother", "son"}, "family"));
intentions.emplace_back(Tag({"car", "bus", "airplan"}, "transportation"));
for_each( std::execution::par
, std::begin(input)
, std::end(input)
, [& intentions](const std::string & input_element)
{
for_each( std::execution::par
, std::begin(intentions)
, std::end(intentions)
, [& input_element](Tag & intention){
if(!intention.m_Found){
if(intention.m_Context.find(input_element)!=intention.m_Context.end()){
intention.m_Found = true;
}
}
}
);
}
);
for_each( std::execution::seq
, std::begin(intentions)
, std::end(intentions)
, [](Tag & intention){
if(intention.m_Found){
std::cout<<intention.m_Name;
}
}
);
return 0;
}
|
69,639,021 | 69,639,101 | Comparator for member variable of type std::set that requires access to other member variables | I have a class ShapeDisplay that stores a set of Rectangles. I would like to store them sorted, therefore I use a std::set. My intention is to provide a custom comparator, which compares the origin (x, y) of the rectangle to a reference point (x, y) in the display.
However, in order to achieve this, the comparator needs access to m_reference. How do I use a custom comparator, that needs access to the class members? Is my design flawed? I know there are newer ways to provide the comparator as in this link, but that doesn't solve my access issue.
Alternatively, I could just have a std::vector that I keep sorted, such that each new Rectangle is inserted in the right position. But since std::set::insert() should do that automatically with a custom comparator, I would prefer that.
Thank you.
struct Point
{
int x;
int y;
};
struct Rectangle
{
int x;
int y;
int width;
int height;
};
class ShapeDisplay
{
void insertShape(Rectangle rect)
{
m_shapes.insert(rect);
}
void setReference(Point reference)
{
m_reference = reference;
}
private:
struct CenterComparator
{
bool operator() (const Rectangle & a, const Rectangle & b) const
{
double distA = std::sqrt(std::pow(a.x - m_reference.x, 2)
+ std::pow(a.y - m_reference.y, 2));
double distB = std::sqrt(std::pow(b.x - m_reference.x, 2)
+ std::pow(b.y - m_reference.y, 2));
return distA < distB;
}
};
std::set<Rectangle, CenterComparator> m_shapes;
Point m_reference;
};
| CenterComparator isn't related to ShapeDisplay, it isn't aware of its members and it isn't derived from ShapeDisplay. You need to provide CenterComparator with its own reference Point. You then need to provide an instance of CenterComparator whose reference point is set.
Note that if you change that comparator's reference point in any way you will break std::set's sorting resulting in Undefined Behavior if you try to use it. So whenever setReference is called, you need to create a new set with a new comparator and copy over the old set.
Here is your code, adapted with these changes. I assumed you meant setReference and insertShape to be part of the public interface.
#include <cmath>
#include <set>
struct Point
{
int x;
int y;
};
struct Rectangle
{
int x;
int y;
int width;
int height;
};
class ShapeDisplay
{
public:
void insertShape(Rectangle rect)
{
m_shapes.insert(rect);
}
void setReference(Point reference)
{
m_reference = reference;
// Create a comparator using this new reference
auto comparator = CenterComparator{};
comparator.reference = m_reference;
// Create a new set
auto new_shapes = std::set<Rectangle, CenterComparator>(
std::begin(m_shapes), std::end(m_shapes), // Copy these shapes
comparator); // Use this comparator
m_shapes = std::move(new_shapes);
}
private:
struct CenterComparator
{
bool operator() (const Rectangle & a, const Rectangle & b) const
{
double distA = std::sqrt(std::pow(a.x - reference.x, 2)
+ std::pow(a.y - reference.y, 2));
double distB = std::sqrt(std::pow(b.x - reference.x, 2)
+ std::pow(b.y - reference.y, 2));
return distA < distB;
}
Point reference;
};
std::set<Rectangle, CenterComparator> m_shapes;
Point m_reference;
};
|
69,639,305 | 69,639,413 | How can i save every move that was made "a, w, s, or d" to an array? | I want to save every move 'char' to an array, and then call back all arrays to see the history
cout << "=== Chose ===" << endl;
cout << "Choose were to GO" << endl;
cout << "a, w, s, or d" << endl;
cout << endl;
cin >> Сhoice_1;
if (tolower(Сhoice_1) == 'a')
{
cout << "You made a step to the left" << endl;
value1 = -1;
if (value1 < 0) break;
}
if (tolower(Сhoice_1) == 's')
{
cout << "You made a step back" << endl;
value1 = -1;
if (value1 < 0) break;
}
if (tolower(Сhoice_1) == 'w')
{
cout << "You made a step foward" << endl;
value1 = -1;
if (value1 < 0) break;
}
if (tolower(Сhoice_1) == 'd')
{
cout << "You made a step to the right" << endl;
value1 = -1;
if (value1 < 0) break;
}
if (LifeOptionMain <= 0)
{
value1 = -1;
if (value1 < 0) break;
}
I tried for loop
for (int i = 0; i < 10; i++)
{
move[i + 1];
move[i] = Сhoice_1;
}
but all elements are only one symbol, last input symbol, if last was a then output will be
a
a
a
....
what am I doing wrong??? please help.
| You could run into trouble with the length of your array, but this would work.
char moveArray[1024];
int moveArrayIndex = 0;
...
cin >> Сhoice_1;
moveArray[moveArrayIndex++] = Choice_1;
moveArray[moveArrayIndex] = 0; // This makes it a printable string.
...
The problem with this is that you're flow off the end of your array if there are more moves than you made space for. A different data structure would be safer.
std::vector<char> moveArray;
cin >> Choice_1;
moveArray.push_back(Choice_1);
However, this is probably using techniques you're not ready for yet.
|
69,639,392 | 69,639,699 | Getting value from Edit to work with region | I needed to divide the picture into sectors and count the number of black dots in each of them. I use regions for this. Can I do this with the Edit input field somehow?
HRGN region [n];
HRGN requires a constant value like
const n = 35;
Please, help if it is possible to somehow link HRGN with Edit, for example, if Edit is set as follows:
int n = Edit1-> Text.ToIntDef (0);
| I think you are asking how to allocate an array using a TEdit to specify the array's count, is that right?
Consider using T(C)SpinEdit instead of TEdit for numeric input.
You can allocate an array dynamically at runtime using new[]:
HRGN *region = NULL;
...
int n = Edit1->Text.ToInt(); // or SpinEdit1->Value
region = new HRGN[n];
// use region as needed...
delete[] region;
Or better, use std::vector, or System::DynamicArray, instead:
#include <vector>
std::vector<HRGN> region;
...
int n = Edit1->Text.ToInt(); // or SpinEdit1->Value
region.resize(n);
// use region as needed...
// freed automatically when out of scope...
#include <sysdyn.h>
DynamicArray<HRGN> region;
...
int n = Edit1-> Text.ToInt(); // or SpinEdit1->Value
region.Length = n;
// use region as needed...
// freed automatically when out of scope...
|
69,640,526 | 69,640,618 | Prime numbers - I need clarification on code implementation | This is the code I know:
bool checkPrime(int n) {
bool prime = true;
for (int i = 2; i < n; i++) {
if ((n%i) == 0) {
prime = false;
}
}
return prime;
}
But is this ok if you’re looking for prime numbers:
List<int> arr = [2, 3, 5, 7]; // Already known
int n = 30; // Between 1 to 30. It could be any number
for (int i = 2; i < n; i++) {
if (i % 2 != 0 && i % 3 != 0 && i % 5 != 0 && i % 7 != 0) {
arr.add(i);
}
// Then maybe some code for numbers less than 8
}
print(arr);
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
And also is there much difference in time complexity?
| Your code is incorrect.
This code only works because you are taking the value of n as 30, for a greater number like 1000 this will produce an incorrect result.
List arr = [2,3,5,7]; // already known
int n = 1000; // between 1 to 1000 it could be any number
List<int> arr = [2,3,5,7];
for (int i = 2; i < n; i++) {
if (i % 2 != 0 && i % 3 != 0 && i % 5 != 0 && i % 7 != 0){
arr.add(i);
}
//Then maybe some code for numbers less than 8
}
print(arr);
Your code will return 231 prime numbers when there are actually only 168 prime numbers.
This is because you are not considering the future prime numbers that can only be divided by a prime number between 7 to that number.
eg: 121 will be returned by you as prime but it is a multiple of 11
Extending your pattern.
Though this will be faster since it has reduced a number of division operations but due to two loops, it will still be N square.
Here I am simply only dividing numbers from the existing prime numbers collection and adding them in the collection if prime is found tobe used in next iteration for division.
List < int > arr = [2]; // taking 2 since this is the lowerst value we want to start with
int n = 30; // n can between 2 to any number
if (n < 3) {
print(arr); // can return from here.
}
// since we already have added 2 in the list we start with next number to check that is 3
for (int i = 3; i < n; i++) {
bool isPrime = true;
for (int j = 0; j < arr.length; j++) { // we iterate over the current prime number collection only [2] then [2,3]...
if (i % arr[j] == 0) { // check if number can be divided by exisiting numbers
isPrime = false;
}
}
if (isPrime) { // eg: 2 cant divide 3 so we 3 is also added
arr.add(i)
}
}
print(arr);
You can look a faster pattern here.
Which is the fastest algorithm to find prime numbers?
|
69,640,788 | 69,643,297 | Casting a reference to a pointer to a reference to a void* | Is the following well defined behavior?
#include <cstdlib>
#include <iostream>
void reallocate_something(void *&source_and_result, size_t size) {
void *dest = malloc(size);
memcpy(dest, source_and_result, size);
free(source_and_result);
source_and_result = dest;
}
void reallocate_something(int *&source_and_result, size_t size) {
// I the cast safe in this use case?
reallocate_something(reinterpret_cast<void*&>(source_and_result), size);
}
int main() {
const size_t size = 4 * sizeof(int);
int *start = static_cast<int*>(malloc(size));
*start = 0;
std::cout << start << ' ' << *start << '\n';
reallocate_something(start, size);
std::cout << start << ' ' << *start << '\n';
return 0;
}
The code uses a reinterpret_cast to pass a reference to a pointer and re-allocate it, free it, and set it to the new area allocated. Is this well defined?
In particular A static_cast would work if I did not want to pass a reference, and that would be well defined.
The tag is C++, and I'm asking about this code as-is within the C++ standard.
|
Is the following well defined behavior?
No, it's not. You can't interpret int * pointer with void * handle, int and void are not similar types. You can convert an int * pointer to void * and back. If your function takes a reference, to do the conversion you need a new temporary variable of type void * to hold the result of the conversion, and then you have to assign it back, like in the other answer https://stackoverflow.com/a/69641609/9072753 .
Anyway, just make it a template, and write nice C++ code with placement new. Something along:
template<typename T>
void reallocate_something(T *&pnt, size_t cnt) {
T *dest = reinterpret_cast<T *>(malloc(cnt * sizeof(T)));
if (dest == NULL) throw ...;
for (size_t i = 0; i < cnt; ++i) {
new (dest[i]) T(pnt[i]);
}
free(static_cast<void*>(pnt));
pnt = dest;
}
|
69,640,896 | 69,640,990 | How to understand the first type of pair? | I am learning C++ recently and am confused by this data type:
pair<map<string, size_t>::iterator, bool> ret =
word_count.insert(make_pair(word, 1));
It should be easy to see that we’re defining a pair and that the second type of the
pair is bool. The first type of that pair is a bit harder for me to understand.
If there were no scope operator or iterator, it would be easy. But after adding :: iterator is it iterator type or the map<string, size_t> type?
| iterator is a nested type inside of the std::map class.
The first member of the pair is an iterator to an element in the map. The insert() method returns an iterator to the element that was inserted, or to the element that prevented the insertion.
The bool in the pair indicates whether the insertion was successful or not, ie whether the returned iterator is to a new element or an existing element, respectively.
|
69,640,911 | 69,640,946 | Should I use the "delete" for the object member which initialized by "new" operator in constructor? | I have a question about new and delete:
Should I use delete for the input parameter or member object, e.g.:
https://github.com/jwbecalm/Head-First-Design-Patterns-in-CPP/blob/main/ch01_Strategy/main.cpp
Should I use delete on the object allocated by new FlyNewWay()?
// change behavior in runtime
mallardDuck->setFlyBehavior(new FlyNewWay());
// create custom MallarDuck on stack.
MallarDuck rocketDuck = MallarDuck(new FlyWthRocket(), new NewQuack());
and in MallardDuck constructor:
https://github.com/jwbecalm/Head-First-Design-Patterns-in-CPP/blob/main/ch01_Strategy/MallarDuck.cpp
MallarDuck:: MallarDuck(){
cout << "in MallarDuck:: MallarDuck()" << endl;
// 为MallarDuck 赋值其特有的行为
m_flyBehavior = new FlyWithWings();
m_quackBehavior = new SimpleQuack();
}
SHould I use delete to free m_flyBehavior and m_quackBehavior? but these two are members of object.
I can easily add delete in destructor of MallarDuck.
MallarDuck::~MallarDuck(){
cout << "in ~MallarDuck()" << endl;
delete m_flyBehavior;
delete m_quackBehavior;
}
but how about the input parameter mentioned in the first code block? or is this way to design and pass value not recommended? do you have some suggestions?
the setFlyBehavior() is as follows, if I add delete fb, it will delete m_flyBehavior also for my understanding because both fb and m_flyBehavior point to the same memory address.
void Duck::setFlyBehavior(FlyBehavior* fb){
m_flyBehavior = fb;
cout << "in Duck::setFlyBehavior()" <<endl;
}
after the setFlyBehavior(), both fb and m_flyBehavior point to the same memory address. so in the deconstructor: ~MallarDuck(), if I delete m_flyBehavior, the input parameter fb where it point to will be free too.
So, the delete in deconstructor ~MallarDuck() is enough. thx .
| Yes whenever you use new keyword to allocate some memory then you must always use delete to free up that memory later when no longer needed. Otherwise you will have a memory leak as in your program. In your case you should use delete inside the destructor in the MallarDuck.cpp .
Other solution would be to use smart pointers like unique_ptr so that you don't have to explicitly free the memory.
unique_ptr`'s syntax would something like:
unique_ptr<FlyWithWings> m_flyBehavior(new FlyWithWings());
In case you are confused about whether there is a memory leak or not, you can just add a cout statement in the destructor of FlyWithWings and SimpleQuack to confirm whether the destructor is called on these objects or not. Then accordingly you can use smart pointers if needed.
Steps to confirm if you have memory leak
Add some std::cout<<"destructor ran; statement inside the destructors of FlyWithWings and SimpleQuack.
Also, in this case don't use delete explicitly on the data members inside the destructor of MallarDuck.
Then if you see that the destructor is not ran on the data members m_flyBehavior and m_quackBehavior this will mean you have a memory leak and you need to use delete explicitly on the appropriate data members in the destructor of MallarDuck.
Answer to your Edit
how about the input parameter mentioned in the first code block?
For the statement mallardDuck->setFlyBehavior(new FlyNewWay()); you can use the following code:
void Duck::setFlyBehavior(FlyBehavior* fb){
//delete the old memory but note again we should check whether the pointer is valid or not
//check for a valid pointer
if (m_flybehavior)
{
delete m_flybehavior;//free the old memory
}
m_flyBehavior = fb;//so m_flybehavior points to some new memory
//no need to use delete now on m_flybehavior because in the destructor ~MallarDuck() you have delete m_flybehavior
cout << "in Duck::setFlyBehavior()" <<endl;
}
And for the statement
MallarDuck rocketDuck = MallarDuck(new FlyWthRocket(), new NewQuack());
as the MallarDuck's destructor have delete for the data members, it will free up that memory. Also this assumes the input parameters are assigned to the data members.
|
69,641,196 | 69,750,186 | Configure vscode to build and run c++ in one terminal | I installed mingw64 toolchain with MSYS2, and managed to successfully run my code from vscode. However, running it creates two terminals, one for building and one for running the generated file: C/C++: g++.exe build active file and cppdbg: main.exe.
cppdbg: main.exe leaves the text from the previous runs and "presentation" { "clear": true } in launch.json doesn`t help.
since build and run are not related, it's possible that the build will fail and the old .exe will be launched without me noticing it.
So I'm looking for a way to configure vscode to build and run the app in one terminal, or maybe redirect the compiler output to the output tab. Anything similar to how it's done in other languages.
Also, how can I configure it to run without debugging by default? In launch.json, "configurations" require a "type" parameter, which has only one option, "cppdbg" - why is there no release option?
| You are asking two questions and I can answer both.
How do I build and debug the application, by making sure that it is launched only when the build is successful?
How do I configure it to run the application similarly?
Let me answer 2 first.
To solve this, you need the dependsOn property of tasks. For example, this is the content of my tasks.json file:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks":
[
{
"label": "Debug_Build",
"type": "shell",
"command": "g++ -g ./src/main.cpp -o ./bin/a.out",
},
{
"label": "Run main()",
"type": "shell",
"command": "./bin/a.out",
"dependsOn":"Debug_Build" //Previous task is run first, and then this one if previous was successful.
}
]
}
Notice that the second task (which is responsible for running the program) has dependsOn property which behaves exactly as you require: It will run only when the dependsOn task is successful (Which here is the build task)
To run the tasks, you can use the Command Palette to Run
Tasks>Run main()
to launch your task. Personally, I prefer using the extension Tasks, which creates a button for each task in the tasks.json file on the status bar of VS Code.
Now to answer 1, we use a similar property in the launch configuration json file: preLaunchTask
This will be exactly what you need: It will run the debugging only if the preLaunchTask was successful.
My launch.json file is as follows:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/bin/a.out",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "Debug_Build", //This is the part you need
}
]
}
So to summarize, you will need to create tasks.json and launch.json files in your workspace. In the tasks.json file, declare a "build" task, declare the "run" task which depends on the "build" task using the dependsOn property. Finally, in the launch.json file, refer the "build" task in the preLaunch property.
|
69,641,336 | 69,646,291 | How do I make the operating system save my credentials when I use WNetAddConnection2 or WNetAddConnection3? | I wrote a window to enter my username and password to login.
I can't save the credential when I use the following method, what should I do
NETRESOURCEW net_resource {0};
net_resource.dwType = RESOURCETYPE_DISK | RESOURCETYPE_ANY;
TCHAR szRemotePath[MAX_PATH] {0};
_tcscpy_s(szRemotePath, MAX_PATH, remote_path.toStdWString().c_str());
net_resource.lpRemoteName = szRemotePath;
status_code = ::WNetAddConnection2(&net_resource, password.toStdWString().c_str(), user.toStdWString().c_str(),
CONNECT_UPDATE_PROFILE | CONNECT_INTERACTIVE | CONNECT_COMMANDLINE | CONNECT_CMD_SAVECRED);
| You need to write the credentials into the credential vault, e.g. with CredWriteDomainCredentials. See my answer in this question for an example (written in Delphi but should be very straightforward to convert to C/C++)
|
69,641,471 | 69,641,634 | Variadic macro for checking if variable equals one of variadic arguments | I'm currently working on a WebGL-like OpenGL wrapper in c++, which involves verifying that arguments are actually valid. The problem, more or less, is that OpenGL has a ton, and I'm not exaggerating here, of valid arguments for certain functions.
(Image of a naive conditional (possible internalformat constants for glTexImage2D, if you're interested. I literally wrote a JS table parser/conditional maker for a few of those) to make my point. That's an assert...)
The logic of such checks is simple enough:
bool check(const unsigned int var)
{
return var == CONSTANT_1 || var == CONSTANT_2 || var == CONSTANT_...;
}
But, as per the above example, this can stretch for up to 84 possible constants, which is... yeah. And I'm fully aware that a macro wouldn't cut this down by an absurd amount, but it would still make a difference, and I feel like it would be cleaner too. Not to mention the possibility of other macros of a similar fashion with different operators.
So my idea was to use a macro. After all, this check would be trivial to do at runtime, with a std::initializer_list``, std::vector, std::array` or some other container, but since all of these constants are known at compile time, I feel as though this is unnecessary.
Since the number of possible constants is variable, I see no way of not using a variadic macro. Yet I don't know how I would accomplish this. One possible way I thought of doing this is basically overloading a macro based on the number of arguments (akin to this), but this seems unnecessarily complex.
In essence, I'm looking for a macro that would fulfill the following:
MACRO(var, CONSTANT_1, CONSTANT_2, CONSTANT_3)
expands to
var == CONSTANT_1 || var == CONSTANT_2 || var == CONSTANT_3
with any number of constants (important!, and the hard part).
| You might want to use C++17 fold expression:
template<class... Args>
bool check(const unsigned int var, const Args&... args)
{
return ((var == args) || ...);
}
Then you can invoke something like this:
check(var, CONSTANT_1, CONSTANT_2, CONSTANT_3);
|
69,641,553 | 69,644,294 | Decision tree- delete from a specific node | I have a decision tree that includes node and answer that leads us to another nodes. Answers begin with ":" and nodes are the rest.
I have to do a function that delete a subtree from a specific node. For example If I want to delete node "brand?", I want that after that the tree will print from car-color? to blue-is-beautiful
I don't success doing this deletion in the right way because I think I have to delete also the answer red and don't know how to do that.
class Answer
{
public:
string ans;
Node* son;
Answer(string s, Node* p) { ans = s; son = p; }
};
class Node
{
public:
Node(string v) { isLeaf = true; value = v; }
list<Answer*> answersList;
string value;
bool isLeaf;
};
void Tree::del(Node* t)
{
if (t->isLeaf)
return;
for (list<Answer*>::iterator it = t->answersList.begin(); it != t->answersList.end(); it++)
{
del((*it)->son);
delete((*it));
*it = NULL;
}
if (t)
{
delete t;
t = NULL;
}
}
| Now having understood the problems (highly restrictive requirements and what is causing your code to fail), I now have an answer for you.
The issue is, that you need to remove the node you've deleted from the collection it is stored in.
For this purpose, you need to use an alternate version of your search to detect, which child has the value you are looking for.
Due to the requirement of 'not adding any additional functions', there are two ways to go about this.
One is to employ recursion using an anonymous function, the other is 'check the child prior to diving into it'.
The following code fragment uses a DIY-Lambda-Functor, which employs the recursion method.
void Tree::deletefromNode(string val)
{
bool didFindValue = false;
std::function<bool (Node *, const string &)> functor;
class Functor
{
public:
Functor(Tree *owner, bool &didFindValue) : owner(owner), didFindValue(didFindValue)
{
}
bool deleteFromNode(Node *node, const string &value)
{
bool foundMatch = false;
if (node)
{
foundMatch = (node->value == value);
if (!foundMatch)
{
for (list<Answer*>::iterator it = node->answersList.begin(); it != node->answersList.end();)
{
Node *childNode = (*it)->son;
if (deleteFromNode(childNode, value))
{
owner->del(childNode);
it = node->answersList.erase(it);
didFindValue = true;
}
else
it++;
}
}
}
return foundMatch;
}
private:
Tree *owner;
bool &didFindValue;
};
Functor(this, didFindValue).deleteFromNode(root, val);
if (didFindValue)
cout << "Value not found" << endl;
}
|
69,641,838 | 69,819,339 | TCP packet drop (ns3) | I am new to ns3 network simulator and wanted to know how to get the number of packet drops in a TCP connection. I know of the following command:
devices.Get (1)->TraceConnectWithoutContext ("PhyRxDrop", MakeBoundCallback (&RxDrop, stream));
But this is helpful only for a single TCP connection over a p2p link. In my topology, there is a single p2p connection but 2 applications using TCP over that same p2p link and I would like to know individually for each TCP connection the number of dropped packets. I have researched online quite a lot but was unable to find any resources. Kindly point to some resources or give the class name which I can use to detect TCP connection-specific packet losses.
The above command as of now combines the packet losses for both the connections and outputs them to the stream because they are over the same p2p link.
| The usage of RxDrop tells me you're using referring to fourth.cc in the ns-3 tutorial. Connecting to the PhyRxDrop TraceSource will result in the requested CallBack being invoked for each dropped packet. ns-3 doesn't have a packet filter such that the CallBack would only be invoked for some packets.
However, you can determine which connection a packet corresponds to. Simply strip the packet headers, and inspect the port numbers. Remember every connection is defined by a unique 4-tuple: (host IP, host port, destination IP, destination port).
static void
RxDrop(Ptr<const Packet> packet) {
/*
* Need to copy packet since headers need to be removed
* to be inspected. Alternatively, remove the headers,
* and add them back.
*/
Ptr<Packet> copy = packet->Copy();
// Headers must be removed in the order they're present.
PppHeader pppHeader;
copy->RemoveHeader(pppHeader);
Ipv4Header ipHeader;
copy->RemoveHeader(ipHeader);
TcpHeader tcpHeader;
copy->RemoveHeader(tcpHeader);
std::cout << "Source IP: ";
ipHeader.GetSource().Print(std::cout);
std::cout << std::endl;
std::cout << "Source Port: " << tcpHeader.GetSourcePort() << std::endl;
std::cout << "Destination IP: ";
ipHeader.GetDestination().Print(std::cout);
std::cout << std::endl;
std::cout << "Destination Port: " << tcpHeader.GetDestinationPort() << std::endl;
}
|
69,642,411 | 69,642,522 | Can I use dijkstra_shortest_paths in BGL on "cyclic" directed graph | At first, Sorry for my english :(
my graph's spec is
cyclic
directed
edge weight is positive or zero
As I know dijsktra algorithm cannot find shortest path of "cyclic" graph. But there is no that restriction in BGL docs (https://www.boost.org/doc/libs/1_77_0/libs/graph/doc/dijkstra_shortest_paths.html)
So I wonder I can find shortest paths of this graph by using dijkstra_shortest_paths in BGL.
thanks.
| Yes, you can in fact use the method.
Dijkstra works with cycles in graphs as long as they are positive
The documentation of the method states, which does not apply given your specs:
Use the Bellman-Ford algorithm for the case when some edge weights are negative
See also https://cs.stackexchange.com/questions/101637/dijkstra-s-shortest-path-algorithm
|
69,642,797 | 70,500,694 | ESP32 Arduino httpSecureClient -1 error at core 0 without reason why | I'm having an issue with the httpsecureclient library for the ESP in the Arduino IDE.
I try to send http requests to a https domain (that doesn't change) and works alot of times just fine.
Like I do some HTTP calls to obtain certain data to let the ESP do it's thing. But when I want to let the ESP post a payload to a server, using the WiFiClientSecure and HTTPClient, it sometimes works without issues, but all of a sudden, it stops working and throws me the well known, nothing saying -1 response code...
The code I ues to send a heartbeat is the following;
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
WiFiClientSecure ApiClient;
HTTPClient ApiHttpClient;
StaticJsonDocument<256> doc;
doc["mac"] = deviceMacAddress;
doc["key"] = DEVICE_SECRET;
doc["type"] = DIGITAL_HQ_SOFTWARE_TYPE;
String heartbeatData;
serializeJson(doc, heartbeatData);
ApiClient.setInsecure(); //skip verification of SSL cert
Serial.println("Sending Heartbeat");
ApiHttpClient.begin(ApiClient, DIGITAL_HQ_HEARTBEAT_ENDPOINT);
ApiHttpClient.addHeader("Content-Type", "application/json");
ApiHttpClient.setUserAgent(DIGITAL_HQ_USER_AGENT);
int responseCode = ApiHttpClient.POST(heartbeatData); // just post, Don't care about the response.
if (responseCode != 200) {
failedApiCalls ++;
}
Serial.print("ResponseCode from heartbeat: ");
Serial.println(responseCode);
// Free resources
ApiHttpClient.end();
this code runs on core 0, via the following function;
xTaskCreatePinnedToCore(sendHeartBeat, "Send Heartbeat", 20000, NULL, 25, &heartBeatTask, 0);
I do call the heartbeat once in the main core, then it works, but then on the second core, it sometimes does, but other times, it doesnt.
There is nothing too fancy about this, I think and I really can't seem to figure this one out...
Side notes:
There is an MQTT connection running to the AWS IoT hub, on core 1, where I don't have any issues with.
| I currently run into same troubles after updating the libraries, old code for esp32 http clients stopped to work with the same symptoms.
I could solve this by switching to simply use HTTPClient only, without WiFiClientSecure. And it works with https.
#include <HTTPClient.h>
#include <Arduino_JSON.h>
void getPricesFromKraken(){
String url = "https://api.kraken.com/0/public/Ticker?pair=DOGEUSD,XBTUSD";
HTTPClient http;
JSONVar data;
http.begin(url.c_str());
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
data = JSON.parse(payload);
Serial.println(data);
}
else {
Serial.printf("http response code: %d\n", httpResponseCode);
}
http.end();
}
|
69,642,941 | 69,643,678 | Clarification on difference in ODR rules for structs in C and C++ | I am aware of how ODR, linkage, static, and extern "C" work with functions. But I am not sure about visibility of types since they cannot be declared static and there are no anonymous namespaces in C.
In particular, I would like to know the validity of the following code if compiled as C and C++
// A.{c,cpp}
typedef struct foo_t{
int x;
int y;
} Foo;
static int use_foo()
{
Foo f;
f.x=5;
return f.x;
}
// B.{c,cpp}
typedef struct foo_t{
double x;
} Foo;
static int use_foo()
{
Foo f;
f.x=5.0;
return f.x;// Cast on purpose
}
using the following two commands (I know both compilers autodetect the language based on extensions, hence the different names).
g++ -std=c++17 -pedantic -Wall -Wextra a.cpp b.cpp
gcc -std=c11 -pedantic -Wall -Wextra a.c b.c
Versions 8.3 happily compile both without any errors. Clearly, if both struct symbols have external linkage, there is ODR violation because the definitions are not identical. Yes, compiler is not required to report it, hence my question because neither did.
Is it valid C++ program?
I do not think so, that is what anonymous namespaces are for.
Is it valid C program?
I am not sure here, I have read that types are considered static which would make the program valid. Can someone please confirm?
C,C++ Compatibility
If these definitions were in public header files, perhaps in different C libraries, and a C++ program includes both, each also in a different TU, would that be ODR? How can one prevent this? Does extern "C" play any role?
| I will use for references the n1570 draft for C11 for the C language and the draft n4860 for C++20 for the C++ language.
C language
Types have no linkage in C: 6.2.2 Linkages of identifiers §6:
The following identifiers have no linkage: an identifier declared to be anything other than
an object or a function...
That means that the types used in a.c and b.c are unrelated: you correctly declare different objects in both compilation units.
C++ language
Types do have linkage in C++. 6.6 Program and linkage [basic.link] says (emphasize mine):
§2:
A name is said to have linkage when it might denote the same object, reference, function, type, template,
namespace or value as a name introduced by a declaration in another scope
§4
An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has
internal linkage. All other namespaces have external linkage. A name having namespace scope that has not
been given internal linkage above and that is the name of...
a named class......
has its linkage determined as follows:
— if the enclosing namespace has internal linkage, the name has internal linkage;
— otherwise, if the declaration of the name is attached to a named module (10.1) and is not exported (10.2),
the name has module linkage;
— otherwise, the name has external linkage
The types declared in a.cpp and b.cpp share the same identifier with external linkage and are not compatible: the program is ill-formed.
That being said, most common compiler are able to compile either C or C++ sources, and I would bet a coin that they try hard to share most of the implementation of both languages. For that reason, I would trust real world implementation to produce the expected resuls even for C++ language. But Undefined Behaviour does not forbid expected results...
|
69,642,963 | 69,643,213 | Recursive function for digit sum in c++ | Tried writing a recursive function for digit sum in c++ ; ended up getting the last digit instead. Can anyone suggest fixes..
'''
#include<iostream>
using namespace std;
int dsum (int n, int sum)
{
if(n>0)
{
sum = sum + (n%10);
n = n/10;
return(n ,sum);
}
else return sum;
}
int main()
{
int i = 345;
int s = dsum (i,0);
cout<<"Sum is "<<s;
return 0;
}
'''
| You didn't call the recursion as seen in here:
int dsum (int n, int sum)
{
if(n>0)
{
sum = sum + (n%10);
n = n/10;
return(n ,sum); // <-- this line
}
else return sum;
}
Notice you return(n ,sum); instead of return dsum(n ,sum);. return(n ,sum); fist evaluates the left operand: n and then the right operand: sum. Since there's nothing to evaluates, it will returns the result of the right operand, which is sum.
|
69,643,315 | 69,643,414 | Collect all boost fusion map keys into a std::tuple | Consider this snippet:
#include <boost/fusion/container/map.hpp>
#include <boost/fusion/sequence/intrinsic/at_key.hpp>
#include <boost/fusion/sequence/intrinsic/value_at_key.hpp>
#include <tuple>
struct MyEvents {
struct EventA;
struct EventB;
using EventMap = boost::fusion::map<boost::fusion::pair<EventA, int>,
boost::fusion::pair<EventB, double>>;
};
template <typename T>
struct GetTypes;
template <typename T>
struct GetTypes<boost::fusion::map<...>> {
using type = std::tuple<...>;
};
int main() {
using Map = typename MyEvents::EventMap;
using AllKeys = GetTypes<Map>::type;
return 0;
}
Demo
I want to collect all key types from a boost::fusion::map into a std::tuple.
The keys in this snippet are MyEvents::EventA and MyEvents::EventB, so AllKeys = std::tuple<MyEvents::EventA, MyEvents::EventB>.
How could one do this with template specialization? Do I need some kind of recursive calls?
| You can get the key type of boost::fusion::pair by using T::first_type.
template <typename T>
struct GetTypes;
template <typename... Pairs>
struct GetTypes<boost::fusion::map<Pairs...>> {
using type = std::tuple<typename Pairs::first_type...>;
};
Demo.
|
69,643,551 | 69,643,594 | Does make_shared ignore explicit specifier? | Consider the following example:
#include <iostream>
#include <memory>
struct A
{
explicit A(int x)
{
std::cout << x << std::endl;
}
};
void Foo(A ) {}
std::shared_ptr<A> Foo2(int x)
{
// why does this work?
return std::make_shared<A>(x);
}
int main()
{
A a(0);
Foo(a);
// Foo(1); does not compile
Foo2(2);
}
I have a class A with an explicit marked constructor so that it doesn't convert from int to the class A implicitly. But in a call to std::make_shared I can call and create this class by only passing an int. Why is that possible and is there something wrong in the way how I do it?
| This is expected behavior, because std::make_shared performs direct-intialization, which considers explicit constructors too.
The object is constructed as if by the expression ::new (pv) T(std::forward<Args>(args)...)
Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non-explicit constructors and non-explicit user-defined conversion functions, while direct-initialization considers all constructors and all user-defined conversion functions.
Foo(1); doesn't work because the parameter gets copy-initialized, which won't consider explicit constructors.
|
69,643,998 | 69,644,108 | C++ ifstream is reading last line only | I am working on a program that allows a user to register an account. When a user registers for an account, the username and password are output to a text file "database.txt".
There is also an option for a user to search for their password by inputing their username if they forget their password. I find that this works fine when there is only one user registered in the .txt file database. However, when there is more than one user, the forgot password function returns the password of the most recent registered user, no matter which username is searched.
database.txt looks like this:
user1 111
user2 222
user3 333
No matter which user is entered to find the password, the function will always return 333, which is the most recent registered user's password. How do I fix this so that whichever user is searched, their password will output?
Here is the function:
void forgot()
{
int ch;
system("cls");
cout << "Forgotten? We're here to help." << endl;
cout << "Choose one of the options below: " << endl;
cout << "1. Forgot my password" << endl;
cout << "2. Forgot my username" << endl;
cout << endl;
cout << "Enter your choice: ";
cin >> ch;
switch(ch)
{
case 1: // search for username to find password
{
int count = 0;
string searchUser, su, sp;
cout << "Enter your username: ";
cin >> searchUser;
ifstream searchUserName("database.txt");
while(searchUserName >> su >> sp)
{
if(su == searchUser)
{
count = 1;
}
}
searchUserName.close();
if(count == 1)
{
cout << "Account found!" << endl;
cout << "Your password is: " << sp;
cin.get();
cin.get();
system("cls");
menu();
}
else
{
cout << "Sorry, that user ID does not exist." << endl;
cout << "Please contact our service team for more details." << endl;
cin.get();
cin.get();
system("cls");
menu();
}
break;
}
case 2: // search for password to find username
{
int count = 0;
string searchPass, su2, sp2;
cout << "Enter your password: ";
cin >> searchPass;
ifstream searchPassword("database.txt");
while(searchPassword >> su2 >> sp2)
{
if(sp2 == searchPass)
{
count = 1;
}
}
searchPassword.close();
if(count == 1)
{
cout << "Your password has been found." << endl;
cout << "Your username is: " << su2;
cin.get();
cin.get();
system("cls");
menu();
}
else
{
cout << "Sorry, we couldn't find your password in our database." << endl;
cout << "Please contact our team for more information." << endl;
cin.get();
cin.get();
system("cls");
menu();
}
break;
}
default:
cout << "Invalid choice, please try again." << endl;
system("cls");
forgot();
}
}
| You should break out of the while loop once you have found the user name here:
while(searchUserName >> su >> sp)
{
if(su == searchUser)
{
count = 1;
break; // add this
}
}
Now it will continue to overwrite a previously found user name until searchUserName >> su >> sp is no longer true which is once it encounters EOF in most cases.
The other part of the program has the same problem.
Personnally I would rewrite the code such that the condition whether a matching password has been found or not is part of the loop condition.
|
69,644,031 | 69,644,491 | Can an enum class variable take the full range of integer values? | Sometimes it happens that you want to give names to some integer values, but allow for other values than the named ones. In C++, this is easily achieved with an ordinary enum:
enum { red, green, blue };
int color = 999;
Suppose in some unusual context, you want to use enum class for type checking, but also allow for other values:
enum class color_t { red, green, blue };
color_t color = (color_t)999;
Is this still okay? Or is it the case that, for example, the compiler could choose to base color_t on char rather than int, which would make 999 not a valid value for the base type? If the latter, can this problem be solved by explicitly declaring the base type with enum class color_t: int?
|
[dcl.enum]
8 For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type.
Once the underlying type is fixed, any value in its range is a value of the enumeration. The enumerators are just named constants in that range.
There is some minutiae involved in determining when the underlying type is fixed, but it doesn't apply here. A scoped enumeration always has a fixed type (int if none is given explicitly).
|
69,645,963 | 69,646,192 | templating a random number generator in c++ | I know my code is wrong. I should have uniform_int_distribution<int>, but I need a random number generator that works whatever the type is.
I mean I could generate int and divide them by 10^n to get a float but I dont like the elegance of it.
template <class T>
T aleaGenVal(const T &min,const T &max)
{
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<T> dist(min,max);
return dist(rng);
}
thank you for your help
| std::uniform_int_distribution is only defined for some fundamental integer types, and std::uniform_real_distribution is only defined for the fundamental floating point types.
You could choose between those with std::conditional_t
Unfortunately there are a number of integral types that are not usable with std::uniform_int_distribution, so we have to enumerate the allowed ones.
template <typename> struct has_uniform_distribution : std::false_type;
template <std::floating_point T> struct has_uniform_distribution<T> : std::true_type;
template <> struct has_uniform_distribution<short> : std::true_type;
template <> struct has_uniform_distribution<unsigned short> : std::true_type;
template <> struct has_uniform_distribution<int> : std::true_type;
template <> struct has_uniform_distribution<unsigned int> : std::true_type;
template <> struct has_uniform_distribution<long> : std::true_type;
template <> struct has_uniform_distribution<unsigned long> : std::true_type;
template <> struct has_uniform_distribution<long long> : std::true_type;
template <> struct has_uniform_distribution<unsigned long long> : std::true_type;
template <typename T>
concept uniform_distribution = has_uniform_distribution<T>::value;
template <uniform_distribution T> // or sfinae over has_uniform_distribution in C++ earlier than C++20
T aleaGenVal(T min, T max)
{
std::random_device dev;
std::mt19937 rng(dev());
using dist_t = std::conditional_t<
std::is_integral_v<T>,
std::uniform_int_distribution<T>,
std::uniform_real_distribution<T>
>;
dist_t dist(min,max);
return dist(rng);
}
template <typename T>
T aleaGenVal(T min, T max) = delete;
Alternatively, we could define it for all arithmetic types, by using the widest generator type, and narrowing the result
template <std::arithmetic T> // or sfinae over std::is_arithmetic in C++ earlier than C++20
T aleaGenVal(T min, T max)
{
std::random_device dev;
std::mt19937 rng(dev());
using dist_t = std::conditional_t<
std::is_integral_v<T>,
std::conditional_t<
std::is_signed_v<T>,
std::uniform_int_distribution<long long>,
std::uniform_int_distribution<unsigned long long>>
std::uniform_real_distribution<T>>;
dist_t dist(min,max);
return static_cast<T>(dist(rng));
}
|
69,646,072 | 69,646,227 | how can i use (!(cin>>a)) twice times? | enter image description here
i have used code ( if (!(cin >> arr[i])) ) to check if input from user is different with type int (like string, char) to stop reading into array (arr1), and then i can't use it twice with the second array (arr2), it didn't read input and go straight to cin.clear and return... Can you help me? Thank you very much from it^^
enter image description here
| It seems you mean the following
#include <limits>
//...
if ( not ( std::cin >> arr[i] ) )
{
//...
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
|
69,647,075 | 69,729,897 | Defining namespace in g++ works for some files but fails for others | I won't be able to show any code, but let me explain what is happening:
I'm attempting to compile some software with g++; I have my Makefile setup. There is a main file which calls the necessary functions to get this software working. I have all of my dependencies includes, i.e. all of the header files, all of the .cpp sources, etc.
My problem is, several of the files require me to define a namespace called OPTLEVEL or else g++ errors out.
When I do this, for example: -DOPTELEVEL=GENERIC, those files then no longer error out since I now defined OPTLEVEL; however, several of the other .cpp files now error out because I defined OPTLEVEL. This is all a conundrum and I am not sure what to do.
Here is an example Makefile with how I'm compiling the source files separately; if I were to combine them together in one line with the Define, it would give me an error. This gives me undefined references as I explain below:
HEADERS_DEFINE_NEEDED = /Header/Needed/Path
HEADERS_NO_DEFINE = /Header/No/Define/Path
SOURCES_DEFINE_NEEDED = define1.cpp define2.cpp
SOURCES_NO_DEFINE = noDefine1.cpp noDefine2.cpp
DEFINITIONS = -DOPTLEVEL=GENERIC
all:
g++ -c -I$(HEADERS_DEFINE_NEEDED) $(DEFINITIONS) $(SOURCES_DEFINE_NEEDED)
g++ -c -I$(HEADERS_NO_DEFINE) $(SOURCES_NO_DEFINE)
g++ *.o -o out
I have attempted to compile the .cpp files which require the define separately into their object files. Then I compiled the .cpp files which do not require the defines into their own separate object files, but linking them all together gives undefined references understandably.
The undefined references specifically appear due to the files needed the define now have their namespace looking like GENERIC::FUNCTION_NAME and the ones without the defines looking like OPTLEVEL:FUNCTION_NAME.
I'll take any sort of advice.
Let me know if this doesn't make sense, and I'll attempt to clarify.
Thanks!
EDIT:
Here is an example with what I'm looking at:
define1.cpp
#ifndef OPTLEVEL
#error "Did not define OPTLEVEL
#endif
namespace OPTLEVEL {
class SampleClass : public InheritedClass {
<Code.....>
}
}
| The solution to my original question was to compile the source files that needed OPTLEVEL defined into their own libraries. Then when it came to compiling the main.cpp file, I had to ensure I linked those .a's, and added the linking flags i.e. -llibName.
It took a lot of effort, but this is exactly what needs to be done.
|
69,647,361 | 69,647,462 | how to store struct in a text file in c++ | I want to store the elements of struct into a text file. I have multiple inputs and this is what I have done, however, I can only store the latest inputs but not all the input. Thanks in advance for the help! Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
struct ProcessRecords {
string ID;
int arrival;
int wait;
int burst;
void putToFile() {
ofstream input;
input.open ("process.txt");
input << ID << "\t" << arrival << "\t" << wait << "\t" << burst << endl;
input.close();
}
};
int main() {
int numProcess;
int algo;
cout << "\n\t\t=== CPU SCHEDULING ALGORITHMS ===\n";
cout << "\n\t\tEnter number of processes: ";
cin >> numProcess;
ProcessRecords process[numProcess];
string processID[numProcess];
int arrTime[numProcess];
int waitTime[numProcess];
int burstTime[numProcess];
cout << endl << endl;
for (int i = 0; i < numProcess; i++) {
cout << "\n\tEnter process ID for Process " << i+1 << ":\t ";
cin >> processID[i];
process[i].ID = processID[i];
cout << "\n\t\tEnter arrival time for " << processID[i] << ":\t ";
cin >> arrTime[i];
process[i].arrival = arrTime[i];
cout << "\n\t\tEnter waiting time for " << processID[i] << ":\t ";
cin >> waitTime[i];
process[i].wait = waitTime[i];
cout << "\n\t\tEnter burst time for " << processID[i] << ":\t ";
cin >> burstTime[i];
process[i].burst = burstTime[i];
process[i].putToFile();
}
return 0;
}
Here is my sample output:
| First In C++(by C++ i mean standard C++ and not extensions), the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
For the same reason the following statement is incorrect in your code :
int arrTime[numProcess]; //incorrect because size of array must be fixed and decide at compile time
Second you should append to the text file instead of overwriting it. For opening the file in append mode you can use:
input.open("process.txt", ofstream::app);
You can check here that the program works(append) as you desire, using input.open("process.txt", ofstream::app); . Also do note what i said about the size of array being compile time constant. I have not changed it in the link i have given. You can use std::vector for variable size container.
|
69,648,232 | 69,659,045 | Cannot modify Process DACL that I own with my code but Process Hacker can | I have a process (let's call it ProcessX) that runs by default with only Terminate, Synchronize, and Query Limited Information permissions.
When I look at ProcessX in Process Hacker, I can see the permission (ACE, Owner, etc). I can see that I'm the owner of ProcessX, I can see the 3 limited permissions associated with it (Terminate, Synchronize, and Query Limited Information), and I can even edit the permissions (for instance, set Full Control on it).
However, when I run the code below to check the DACL of ProcessX, with the same user that owns ProcessX, I'm getting an error code 5 (Access Denied) on the GetSecurityInfo() function.
Same results with AccessChk and Process Explorer on ProcessX.
However, Process Hacker is perfectly able to read the DACL of ProcessX and modify it.
I don't understand. How is that possible? Why is my code unable to read the DACL for ProcessX?
I've read in MS documents that to read the DACL, I must use OpenProcess() with READ_CONTROL.
But READ_CONTROL is not an available ACE on the process for my user. So, I can't open the process with it (OpenProcess() errors if I try, which is logical).
So, I'm the owner of the process, but I can't modify the ACE, but Process Hacker can.
Can anybody help me understand?
#include <windows.h>
#include <accctrl.h>
#include <aclapi.h>
#include <winnt.h>
#include <stdio.h>
#include <lmcons.h>
DWORD AddAceToObjectsSecurityDescriptor (
HANDLE pszObjName, // name of object
SE_OBJECT_TYPE ObjectType, // type of object
LPTSTR pszTrustee, // trustee for new ACE
TRUSTEE_FORM TrusteeForm, // format of trustee structure
DWORD dwAccessRights, // access mask for new ACE
ACCESS_MODE AccessMode, // type of ACE
DWORD dwInheritance // inheritance flags for new ACE
)
{
DWORD dwRes = 0;
PACL pOldDACL = NULL, pNewDACL = NULL;
PSECURITY_DESCRIPTOR pSD = NULL;
EXPLICIT_ACCESS ea;
if (NULL == pszObjName)
return ERROR_INVALID_PARAMETER;
//retrieve user
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
printf(username);
// Get a pointer to the existing DACL.
dwRes = GetSecurityInfo(pszObjName, ObjectType,
DACL_SECURITY_INFORMATION,
NULL, NULL, &pOldDACL, NULL, &pSD);
if (ERROR_SUCCESS != dwRes) {
printf( "GetSecurityInfo Error %u\n", dwRes );
goto Cleanup;
}
// Initialize an EXPLICIT_ACCESS structure for the new ACE.
ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
ea.grfAccessPermissions = dwAccessRights;
ea.grfAccessMode = AccessMode;
ea.grfInheritance= dwInheritance;
ea.Trustee.TrusteeForm = TrusteeForm;
ea.Trustee.ptstrName = pszTrustee;
// Create a new ACL that merges the new ACE
// into the existing DACL.
dwRes = SetEntriesInAcl(1, &ea, pOldDACL, &pNewDACL);
if (ERROR_SUCCESS != dwRes) {
printf( "SetEntriesInAcl Error %u\n", dwRes );
goto Cleanup;
}
// Attach the new ACL as the object's DACL.
dwRes = SetSecurityInfo(pszObjName, ObjectType,
DACL_SECURITY_INFORMATION,
NULL, NULL, pNewDACL, NULL);
if (ERROR_SUCCESS != dwRes) {
printf( "SetSecurityInfo Error %u\n", dwRes );
goto Cleanup;
}
Cleanup:
if(pSD != NULL)
LocalFree((HLOCAL) pSD);
if(pNewDACL != NULL)
LocalFree((HLOCAL) pNewDACL);
return dwRes;
}
int main(int argc, char *argv[])
{
int pid = atoi(argv[1]);
printf("[+] Ensuring we have the proper privs....\n");
HANDLE self = OpenProcess(
PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
FALSE, (DWORD) pid);
if(self != NULL){
printf("process open !\n");
AddAceToObjectsSecurityDescriptor(self, SE_KERNEL_OBJECT, (LPSTR)"S-1-5-21-BLABLALEAKBLALBLA",TRUSTEE_IS_SID, PROCESS_ALL_ACCESS, GRANT_ACCESS, 0);
}
else{
printf("error in opening of the process\n");
}
}
| Problem solved !
I've assumed that READ_CONTROL will be refused because it wasn't available on the DACL of the running process.
Turns out, when you own an object, you have implicit READ_CONTROL and WRITE_DAC permission on it, even if zero ACE are set on the object for the user owning it.
#include <windows.h>
#include <accctrl.h>
#include <aclapi.h>
#include <winnt.h>
#include <stdio.h>
#include <lmcons.h>
DWORD AddAceToObjectsSecurityDescriptor (
HANDLE pszObjName, // name of object
SE_OBJECT_TYPE ObjectType, // type of object
LPTSTR pszTrustee, // trustee for new ACE
TRUSTEE_FORM TrusteeForm, // format of trustee structure
DWORD dwAccessRights, // access mask for new ACE
ACCESS_MODE AccessMode, // type of ACE
DWORD dwInheritance // inheritance flags for new ACE
)
{
DWORD dwRes = 0;
PACL pOldDACL = NULL, pNewDACL = NULL;
PSECURITY_DESCRIPTOR pSD = NULL;
EXPLICIT_ACCESS ea;
if (NULL == pszObjName)
return ERROR_INVALID_PARAMETER;
// Get a pointer to the existing DACL.
dwRes = GetSecurityInfo(pszObjName, ObjectType,
DACL_SECURITY_INFORMATION,
NULL, NULL, &pOldDACL, NULL, &pSD);
if (ERROR_SUCCESS != dwRes) {
printf( "GetSecurityInfo Error %u\n", dwRes );
goto Cleanup;
}
// Initialize an EXPLICIT_ACCESS structure for the new ACE.
ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
ea.grfAccessPermissions = dwAccessRights;
ea.grfAccessMode = AccessMode;
ea.grfInheritance= dwInheritance;
ea.Trustee.TrusteeForm = TrusteeForm;
ea.Trustee.ptstrName = pszTrustee;
// Create a new ACL that merges the new ACE
// into the existing DACL.
dwRes = SetEntriesInAcl(1, &ea, pOldDACL, &pNewDACL);
if (ERROR_SUCCESS != dwRes) {
printf( "SetEntriesInAcl Error %u\n", dwRes );
goto Cleanup;
}else{
printf("SetEntriesAcl SUCCESS !\n");
}
// Attach the new ACL as the object's DACL.
dwRes = SetSecurityInfo(pszObjName, ObjectType,
DACL_SECURITY_INFORMATION,
NULL, NULL, pNewDACL, NULL);
if (ERROR_SUCCESS != dwRes) {
printf( "SetSecurityInfo Error %u\n", dwRes );
goto Cleanup;
}else{
printf("SetSecurityInfo SUCCESS \n");
}
Cleanup:
if(pSD != NULL)
LocalFree((HLOCAL) pSD);
if(pNewDACL != NULL)
LocalFree((HLOCAL) pNewDACL);
return dwRes;
}
int main(int argc, char *argv[])
{
int pid = atoi(argv[1]);
DWORD dwRes = 0;
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
HANDLE self = OpenProcess(READ_CONTROL | WRITE_DAC, FALSE, (DWORD) pid);
if(self != NULL){
printf("process open !\n");
AddAceToObjectsSecurityDescriptor(self, SE_KERNEL_OBJECT, (LPSTR)username,TRUSTEE_IS_NAME, PROCESS_ALL_ACCESS, GRANT_ACCESS, 0);
}
else{
dwRes = GetLastError();
printf("error in opening of the process. Code %u \n", dwRes);
}
}
|
69,648,820 | 69,649,512 | Is passing of a function pointer through a class type in non-type template parameter allowed in C++20? | Recently, after playing around with the C++20 feature of being able to pass class types in non-type template parameters (P0732R2), I've encountered something rather strange.
Consider the following code:
template <typename T>
struct abc {
T p;
consteval abc(T p) : p(p) { }
consteval operator decltype(p)() const {
return p;
}
};
template <abc obj>
consteval auto do_something1() {
return obj();
}
template <auto obj>
consteval auto do_something2() {
return obj();
}
constexpr auto fun() {
return true;
}
int main() {
static_assert(do_something1<&fun>()); // OK in Clang, fails in GCC
static_assert(do_something2<&fun>()); // OK in both GCC and Clang
}
This appears to work as intended with clang however GCC fails to compile this and gives an error saying that fun is not a valid template argument.
However, this answer says that function pointers should be valid template arguments as per the C++ standard.
Which compiler is correct here?
Also, weirdly enough, the same code appears to work on both compilers when modified to work with member functions for some reason.
Note: Something that might be useful to note is that according to this page, GCC's support for P0732R2 is complete while Clang's is still in a partial/experimental stage. So, does this mean that GCC is correct and passing of function pointers through class types in non-type template parameters shouldn't be possible, or am I missing something here?
|
Which compiler is correct here?
Clang is correct, the code as written is valid.
GCC not handling that specific case is a known issue.
|
69,649,035 | 69,649,401 | c++ calculate depth of the function calls that led to the current function | say we have a set of function calls that are executed in the following order similar to a tree. that is func0 call func1 and func2 in order. and func2 results in calling func3, afterwhich func0 continues to its next line for executing func4.
func0 // depth 0
func1 // depth 1
func2 // depth 1
func3 // depth 2
func4 // depth 1
func5 // depth 2
func6 // depth 3
func7 // depth 4
func8 // depth 2
func9 // depth 0
What line of code can I put in each one of these functions to print such depth?
| One way is to create an RAII class that counts the depth, and instantiate it at the top of each function you wish to track. I've done this sort of thing for debugging purposes.
class DepthCounter
{
static int depth;
public:
DepthCounter(const std::string& name)
{
std::cout << std::string(depth*2, ' ') << name << " // depth " << depth << '\n';
++depth;
}
~DepthCounter()
{
--depth;
}
};
int DepthCounter::depth = 0;
You can instantiate this in each function with something like:
DepthCounter dc(__func__);
You can name the instance whatever you wish, but without giving it a variable name it will just be a temporary and get destroyed essentially at the semicolon. By making it a variable, it lives until the function exits by whatever means, whether by falling off the end, an explicit return, or via an exception.
I didn't show all the code (have to leave something for you to do), but the output I got looks like:
func0 // depth 0
func1 // depth 1
func2 // depth 1
func3 // depth 2
func4 // depth 1
func5 // depth 2
func6 // depth 3
func7 // depth 4
func8 // depth 2
func9 // depth 0
|
69,649,469 | 69,649,830 | Ambiguity when inheriting ostringstream | I have a simple struct which inherits from std::ostringstream, in order to handle some values better for databases. If I just inherit, and add in a simple constructor to set widths for precision of doubles, it works fine.
struct myostream : std::ostringstream {
myostream() noexcept( false ) {
this->precision( 6 );
this->setf( ios_base::fixed, ios_base::floatfield );
}
};
Now, I'm trying to add in an operator<< for type double, in order to handle infinity, and NaN.
myostream &operator<<( double val ) {
if ( std::isnan( val ) ) {
*static_cast<std::ostringstream *>( this ) << "'NaN'";
} else if ( std::isinf( val ) ) {
*static_cast<std::ostringstream *>( this ) << ( val < 0 ? "'-Infinity'" : "'Infinity'" );
} else {
*static_cast<std::ostringstream *>( this ) << val;
}
return *this;
}
As soon as I add this function in, I just get ambiguous function calls everywhere, for every type (bool, char, char *, int, etc.).
2>...\include\myostream.hpp(13,14): message : could be 'myostream &myostream::operator <<(double)' (compiling source file ...)
2>C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.30.30704\include\ostream(694,32): message : or 'std::basic_ostream<char,std::char_traits<char>> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,char)' (compiling source file ...)
2>C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.30.30704\include\ostream(775,31): message : or 'std::basic_ostream<char,std::char_traits<char>> &std::operator <<<std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,char)' (compiling source file ...)
2>C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.30.30704\include\ostream(856,32): message : or 'std::basic_ostream<char,std::char_traits<char>> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,_Elem)'
2> with
2> [
2> _Elem=char
2> ] (compiling source file ...)
2>C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.30.30704\include\ostream(898,31): message : or 'std::basic_ostream<char,std::char_traits<char>> &std::operator <<<std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,signed char)' (compiling source file ...)
2>C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.30.30704\include\ostream(909,31): message : or 'std::basic_ostream<char,std::char_traits<char>> &std::operator <<<std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,unsigned char)' (compiling source file ...)
2>C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.30.30704\include\thread(275,26): message : or 'std::basic_ostream<char,std::char_traits<char>> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,std::thread::id)' (compiling source file ...)
2>...: message : or 'built-in C++ operator<<(int, int)'
2>...: message : while trying to match the argument list '(myostream, char)'
So, my question is: how would I go about overriding operator<< for some types, without adding in ambiguity? Is this even possible, or would I need to make a function which returns a string instead?
Edit:
Adding in using std::ostringstream::operator<<; just increases the number of ambiguities.
| Here's one option:
struct myostream : std::ostringstream {
using std::ostringstream::operator<<; // bring in all the member overloads
myostream() noexcept( false ) {
this->precision( 6 );
this->setf( ios_base::fixed, ios_base::floatfield );
}
// call the base class member function explicitly in here:
myostream &operator<<( double val ) {
if ( std::isnan( val ) ) {
std::ostringstream::operator<<("'NaN'");
} else if ( std::isinf( val ) ) {
std::ostringstream::operator<<( val < 0 ? "'-Infinity'" : "'Infinity'" );
} else {
std::ostringstream::operator<<(val);
}
return *this;
}
};
// front-end for all the free operator<< functions:
// (this could be narrowed down to not match on T:s that isn't supported)
template<class T>
myostream& operator<<(myostream& m, const T& x) {
static_cast<std::ostringstream&>(m) << x;
return m;
}
|
69,649,478 | 69,649,496 | -Wunused-but-set-variable is emitted when I use 'auto' and not when I use the corresponding type instead of 'auto' | Please consider the following:
#include <functional>
int main() {
std::function<int(int)> f_sq = [](int i) -> int { return i *= i; }; // No warning
auto f_sub = [](int a, int b) -> int { return a - b; }; // -Wunused-but-set-variable
return 0;
}
Why compiler warns when the auto keyword is used, and/or, in the contrary, why it doesn't when auto is not used?
clang version 12.0.1
gcc (GCC) 11.1.0
Target: x86_64-pc-linux-gnu (artixlinux)
| std::function<int(int)> has a non trivial destructor, so might be a RAII object.
Your lambda (remember, lambda is NOT a std::function) has trivial destructor, so it is not a RAII object, so it is really unused.
You might minimize your example with simpler types to avoid confusion lambda/std::function:
std::vector<int> v = {4, 8, 15, 16, 23, 42}; // No warnings
int n = 42; // -Wunused-but-set-variable
|
69,649,792 | 69,649,954 | How to publish Int16MultiArray from rosserial arduino | I am trying to publish an Int16MultiArray for the ros package mecanum_drive: https://github.com/dudasdavid/mecanum_drive
My issue is that I cant seem to publish the array from my arduino. (I am using Teensy 4.1)
#include <std_msgs/Int16MultiArray.h>
ros::NodeHandle nh;
std_msgs::Int16MultiArray wheel_ticks;
ros::Publisher wheel_ticks_pub("wheel_ticks", &wheel_ticks);
void setup() {
nh.getHardware()->setBaud(115200); //was 115200
nh.initNode(); // init ROS
nh.advertise(wheel_ticks_pub);
}
void loop() {
// put your main code here, to run repeatedly:
//I have tried the code below which uploads to the arduino, but rostopic then says that it dosnt contain any data
/*
short value[4] = {0,100,0,0};
wheel_ticks.data = value;
*/
//I also tryed the code below which uploads, but then the teensy looses its serial port (arduino port says"[no_device] Serial(Teensy4.1)":
/*
wheel_ticks.data[0] = 10;
wheel_ticks.data[1] = 5;
*/
//below gives this error: cannot convert '<brace-enclosed initializer list>' to 'std_msgs::Int16MultiArray::_data_type* {aka short int*}' in assignment
/*
wheel_ticks.data = {0,0,0,1};
*/
wheel_ticks_pub.publish(&wheel_ticks);
nh.spinOnce();
}
Everything I have tried has either not uploaded, uploaded but with serial being messed up, or with it uploading and rostopic echo saying it is empty.
Thanks for looking at this, I hope you can help!
| A very specific limitation of rosserial is arrays have an extra field specifically for data length. This is needed since the data field is implemented as a pointer, thus having no real good way to get data length. The message type actually looks like this
class Int16MultiArray{
Header header;
int data_length;
int16_t * data;
};
So, all you have to do is set the data field before sending a message
#include <std_msgs/Int16MultiArray.h>
ros::NodeHandle nh;
std_msgs::Int16MultiArray wheel_ticks;
ros::Publisher wheel_ticks_pub("wheel_ticks", &wheel_ticks);
void setup() {
nh.getHardware()->setBaud(115200); //was 115200
nh.initNode(); // init ROS
nh.advertise(wheel_ticks_pub);
}
void loop() {
short value[4] = {0,100,0,0};
wheel_ticks.data = value;
wheel_ticks.data_length = 4;
wheel_ticks_pub.publish(&wheel_ticks);
nh.spinOnce();
}
|
69,650,085 | 69,650,343 | Why does Child Class shaddow Parent methods even though parameters are of different type | My parent class holds two functions: On is supposed to be overwritten by the child, the second (same name) just uses as input a different type and than uses the overwritten method. Now I understand that if I define in the child class a method with the same name and same input parameters, it will shadow (is that the right expression?) the parents method. But I can still call the parents method by calling it explicit like: b.A::getSize(...).
My question is: Why does the parent method get shadowed even if the input parameter types are different? Why can't the compiler find the parent method with the correct input types? See the below minimal example.
And bonus question: Is it possible to achieve the behaviour that I can call the parents method without the need of the explicit call and without modifying main(){...} nor class B{...}; nor using different names?
#include <cstdio>
class A{
public:
virtual void getSize(size_t &i) = 0;
void getSize(int &d){
size_t i;
getSize(i);
d = static_cast<int>(i);
}
};
class B : public A{
public:
void getSize(size_t &i) override{
i = 4;
}
};
int main(){
size_t t;
int i;
B b;
b.getSize(t);
b.getSize(i); // error: non-const lvalue reference to type 'size_t' (aka 'unsigned long') cannot bind to a value of unrelated type 'int'
b.A::getSize(i); // this works but is not acceptable (too much changes in production code)
printf("%zu, %d",t,i);
return 0;
}
| You can choose to expose the method with a using statement:
class B : public A
{
// ...
using A::getSize;
}
In your code snippets, you have used uninitialised values in many places, this invokes UB.
|
69,650,183 | 69,650,624 | Why is 1 for-loop slower than 2 for-loops in problem related to prefix sum matrix? | I'm recently doing this problem, taken directly and translated from day 1 task 3 of IOI 2010, "Quality of life", and I encountered a weird phenomenon.
I was setting up a 0-1 matrix and using that to calculate a prefix sum matrix in 1 loop:
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (a[i][j] < x) {lower[i][j] = 0;} else {lower[i][j] = 1;}
b[i][j] = b[i-1][j] + b[i][j-1] - b[i-1][j-1] + lower[i][j];
}
}
and I got TLE (time limit exceeded) on 4 tests (the time limit is 2.0s). While using 2 for loop seperately:
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (a[i][j] < x) {lower[i][j] = 0;} else {lower[i][j] = 1;}
}
}
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
b[i][j] = b[i-1][j] + b[i][j-1] - b[i-1][j-1] + lower[i][j];
}
}
got me full AC (accepted).
As we can see from the 4 pictures here:
TLE result, picture 1 : https://i.stack.imgur.com/9o5C2.png
TLE result, picture 2 : https://i.stack.imgur.com/TJwX5.png
AC result, picture 1 : https://i.stack.imgur.com/1fo2H.png
AC result, picture 2 : https://i.stack.imgur.com/CSsZ2.png
the 2 for-loops code generally ran a bit faster (even in accepted test cases), contrasting my logic that the single for-loop should be quicker. Why does this happened?
Full code (AC) : https://pastebin.com/c7at11Ha (Please ignore all the nonsense bit and stuff like using namespace std;, as this is a competitive programming contest).
Note : The judge server, lqdoj.edu.vn is built on dmoj.ca, a global competitive programming contest platform.
| If you look at assembly you'll see the source of the difference:
Single loop:
{
if (a[i][j] < x)
{
lower[i][j] = 0;
}
else
{
lower[i][j] = 1;
}
b[i][j] = b[i-1][j]
+ b[i][j-1]
- b[i-1][j-1]
+ lower[i][j];
}
In this case, there's a data dependency. The assignment to b depends on the value from the assignment to lower. So the operations go sequentially in the loop - first assignment to lower, then to b. The compiler can't optimize this code significantly because of the dependency.
Separation of assignments into 2 loops:
The assignment to lower is now independent and the compiler can use SIMD instructions that leads to a performance boost in the first loop. The second loop stays more or less similar to the original assembly.
|
69,650,616 | 69,650,688 | How to retrieve the captured substrings from a capturing group that may repeat? | I'm sorry I found it difficult to express this question with my poor English. So, let's go directly to a simple example.
Assume we have a subject string "apple:banana:cherry:durian". We want to match the subject and have $1, $2, $3 and $4 become "apple", "banana", "cherry" and "durian", respectively. The pattern I'm using is ^(\w+)(?::(.*?))*$, and $1 will be "apple" as expected. However, $2 will be "durian" instead of "banana".
Because the subject string to match doesn't need to be 4 items, for example, it could be "one:two:three", and $1 and $2 will be "one" and "three" respectively. Again, the middle item is missing.
What is the correct pattern to use in this case? By the way, I'm going to use PCRE2 in C++ codes, so there is no split, a Perl built-in function. Thanks.
| If the input contains strictly items of interest separated by :, like item1:item2:item3, as the attempt in the question indicates, then you can use the regex pattern
[^:]+
which matches consecutive characters which are not :, so a substring up to the first :. That may need to capture as well, ([^:]+), depending on the overall approach. How to use this to get all such matches depends on the language.†
In C++ there are different ways to approach this. Using std::regex_iterator
#include <string>
#include <vector>
#include <iterator>
#include <regex>
#include <iostream>
int main()
{
std::string str{R"(one:two:three)"};
std::regex r{R"([^:]+)"};
std::vector<std::string> result{};
auto it = std::sregex_iterator(str.begin(), str.end(), r);
auto end = std::sregex_iterator();
for(; it != end; ++it) {
auto match = *it;
result.push_back(match[0].str());
}
std::cout << "Input string: " << str << '\n';
for(auto i : result)
std::cout << i << '\n';
}
Prints as expected.
One can also use std::regex_search, even as it returns at first match -- by iterating over the string to move the search start after every match
#include <string>
#include <regex>
#include <iostream>
int main()
{
std::string str{"one:two:three"};
std::regex r{"[^:]+"};
std::smatch res;
std::string::const_iterator search_beg( str.cbegin() );
while ( regex_search( search_beg, str.cend(), res, r ) )
{
std::cout << res[0] << '\n';
search_beg = res.suffix().first;
}
std::cout << '\n';
}
(With this string and regex we don't need the raw string literal so I've removed them here.)
† This question was initially tagged with perl (with no c++), also with an explicit mention of it in text (still there), and the original version of this answer referred to Perl with
/([^:]+)/g
The /g "modifier" is for "global," to find all matches. The // are pattern delimiters.
When this expression is bound (=~) to a variable with a target string then the whole expression returns a list of matches when used in a context in which a list is expected, which can thus be directly assigned to an array variable.
my @captures = $string =~ /[^:]+/g;
(when this is used literally as shown then the capturing () aren't needed)
Assigning to an array provides this "list context." If the matching is used in a "scalar context," in which a single value is expected, like in the condition for an if test or being assigned to a scalar variable, then a single true/false is returned (usually 1 or '', empty string).
|
69,650,647 | 69,650,704 | How to bring std::cout output back to the top after a new line | I have the following menu, which is supposed to update based on whether the user has typed the keys F1 or F2:
int main()
{
bool f1 = false;
bool f2 = false;
while (true)
{
std::cout << "[F1]: " << (f1 ? "ON" : "OFF") << std::endl;
std::cout << "[F2]: " << (f2 ? "ON" : "OFF") << std::endl;
std::cout << "[INS] to quit" << std::endl;
if (GetAsyncKeyState(VK_INSERT) & 0x1)
break;
if (GetAsyncKeyState(VK_F1) & 0x1)
f1 = !f1;
if (GetAsyncKeyState(VK_F2) & 0x1)
f2 = !f2;
Sleep(100);
cleanWindow();
}
return 0;
}
Now, I was using system("cls") before and it was working "fine", but I've been told that I should rather use the Win32 API for cleaning out the console, and so I created cleanWindow() as described by this MSVC article.
DWORD cleanWindow()
{
HANDLE hStdOut;
hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
// Fetch existing console mode so we correctly add a flag and not turn off others
DWORD mode = 0;
if (!GetConsoleMode(hStdOut, &mode))
{
return ::GetLastError();
}
// Hold original mode to restore on exit to be cooperative with other command-line apps.
const DWORD originalMode = mode;
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
// Try to set the mode.
if (!SetConsoleMode(hStdOut, mode))
{
return ::GetLastError();
}
// Write the sequence for clearing the display.
// \x1b[2J is the code for clearing the screen and set cursor to home
DWORD written = 0;
PCWSTR sequence = L"\x1b[2J";
if (!WriteConsoleW(hStdOut, sequence, (DWORD)wcslen(sequence), &written, NULL))
{
// If we fail, try to restore the mode on the way out.
SetConsoleMode(hStdOut, originalMode);
return ::GetLastError();
}
// To also clear the scroll back, emit L"\x1b[3J" as well.
// 2J only clears the visible window and 3J only clears the scroll back.
// Restore the mode on the way out to be nice to other command-line applications.
SetConsoleMode(hStdOut, originalMode);
}
Now, the problem is that the "menu" is at the end of command prompt rather than at the start, as it was with system("cls"):
My question is, how do I do fix this? How do I bring the output back to the top of the shell?
EDIT:
I also edited the cleanWindow() function to write the sequences: \033[2J and L"\033[H" with WriteConsoleW(), which works, but I still get the "blinking" effect just like with system("cls"), which is something I was trying to avoid.
| You can use SetConsoleCursorPosition to set the cursor location back to the top left after doing the clear.
There are also ANSI escape codes (similar to the one you use to clear the screen) that would allow you to reposition the cursor.
"\033[r;cH"
replacing r with the row and c the column to move to. They are 1-based, and default to the top left, so you can use "\033[1;1H" or just "\033[H"
|
69,651,022 | 69,694,907 | pjsip (pjsua2) - opus codec for windows | is it possible to build pjsip with opus-codec for windows as dll?
I built pjsua2.dll alone but seems no way to use opus with it.
| I downloaded opus and pjsip , opened pjsip from visual studio solution, added opus projects to solution and made reference to them from libpjpproject, then build it using this link link
|
69,651,088 | 70,844,055 | clang-format AlignAfterOpenBracket list params | This post asked a similar question about how to modify formatting when there are too many parameters.
I quite like the rust-fmt styling for this. Is there any way to do this with clang-format?
e.g. 1: with AlignAfterOpenBrackets: AlwaysBreak
return_t foo(
some_t param_1, some_t param_2, some_t param_3,
some_t param_4) {
// function body
}
e.g. 2: desired formatting
return_t foo(
some_t param_1,
some_t param_2,
some_t param_3,
some_t param_4
) {
// function body
}
| clang-format AlignAfterOpenBracket just got a new option - BlockIndent (landed on 17/1/22) which does exactly that.
See https://reviews.llvm.org/rG966f24e5a62a:
[clang-format] Add a BlockIndent option to AlignAfterOpenBracket
This style is similar to AlwaysBreak, but places closing brackets on new lines.
For example, if you have a multiline parameter list, clang-format currently only supports breaking per-parameter, but places the closing bracket on the line of the last parameter.
Function(
param1,
param2,
param3);
A style supported by other code styling tools (e.g. rustfmt) is to allow the closing brackets to be placed on their own line, aiding the user in being able to quickly infer the bounds of the block of code.
Function(
param1,
param2,
param3
);
This feature is expected to be released in clang-format-14.
In the meantime you could try getting it from the LLVM nightly builds.
|
69,651,774 | 69,652,959 | Debug assertion failure - C++, using smart pointers | I have been trying to debug this for a while now without any luck. I was hoping to get some help here. Apologies if my question isn't relevant or something, I'm new.
So basically what I have is:
#include <iostream>
template<typename T> class Node {
using NodePtr = std::shared_ptr<Node<T>>;
private:
Node() {}
T value{};
NodePtr parent;
NodePtr child;
public:
Node(const T& value) : value{ value } {}
Node(const T& value, NodePtr child) : Node(value)
{
this->child = child;
if (child != NULL)
{
//problem here?
child->parent = NodePtr(this);
/*The equivalent in C# works perfectly fine:*/
/*this.child = child;
if(child != null) {
child.parent = this;
}*/
}
}
const T& Value() const { return value; }
T& ValueRef() const { return value; }
NodePtr Parent() const { return parent; }
NodePtr Child() const { return child; }
};
template<typename T> std::ostream& operator<<(std::ostream& stream, const Node<T>& node) {
stream << "{" << node.Value() << "}";
return stream;
}
int main()
{
Node<int> n{ 5, std::make_shared<Node<int>>(3) };
std::cout << n;
}
I can implement this easily without using smart pointers, but I'm trying to learn them so there's that.
The assertion that is failing: "is_block_type_valid(header->_block_use)"
Image of the assertion error
Any help would be appreciated, thank you.
| There are a few problems. First, if you want to get a shared_ptr from this, you have to inherit from std::enable_shared_from_this:
template<typename T> class Node : std::enable_shared_from_this<Node<T>> {
// ...
The main problem is that there is a shared_ptr referencing a shared_ptr (the parent to the child, vice-versa). However, shared_ptr are only reference-counted. Take a look at the program below:
#include <iostream>
#include <memory>
struct A;
struct B{
std::shared_ptr<A> sp;
~B(){ std::cout << "B destroyed\n"; }
};
struct A{
std::shared_ptr<B> sp;
~A(){ std::cout << "A destroyed\n"; }
};
int main(){
std::shared_ptr<B> b{};
std::shared_ptr<A> a {b->sp};
b = a->sp;
}
The output is blank! Here is a link to the above program.
To fix, do two additional things: one, change child->parent = NodePtr(this); to the following:
child->parent = this->weak_from_this();
Also, change the type of parent to std::weak_ptr<Node<T>>.
std::weak_ptr is used with problems like this. It doesn't influence the reference count of the std::shared_ptr For more information, go here.
P.S. the error about the is_block_type was caused by shared_ptr, probably because you tried to get a shared_ptr from a raw ptr. Read more about std::shared_ptr here.
|
69,651,777 | 69,652,256 | Generate High Quality textures Realtime C++ | I am having a procedural terrain generation application. Now i want to generate textures for the terrain based on height.
Say i have got 5 textures for different height levels now for every pixel i calculate the the position of it on the mesh then get its height and then decide which texture to sample from.
Note texture is always a square.
In code it will be something like:
for (int i = 0; i < resolution; i++) {
for (int j = 0; j < resolution; j++) {
tex[i * resolution* 3 + j * 3 + 0] = SampleTextureR(i, j);
tex[i * resolution* 3 + j * 3 + 1] = SampleTextureG(i, j);
tex[i * resolution* 3 + j * 3 + 2] = SampleTextureB(i, j);
}
}
Now SampleTextureR(i, j) is just like:
for(TextureData* t : txtures){
if(t.heightl > GetMeshElevation(i, j) && t.heightg < GetMeshElevation(i, j))
return t.sampleR(i, j);
}
return 0;
GetMeshElevation returns height of mesh at a point. t.sampleR() returns unsigned char value of texture's red pixels at (i, j).
heightl is minimum height of the texture
heightg is maximum height of the texture
Now the problem is this this is very slow method. How can i make this fast enough to be done in realtime so that the changes to heightl or heghtg is immediately reflected. the heightl and heightg are for each texture.
These textures can be upto 4K 4096X4096
| Use a varying variable between your vertex and fragment shader. A single float value should suffice, since you're only interested in the height coordinate.
Other than that, introduce 5 uniform varaiables for your textures in the fragment shader and do the calculations on the GPU.
In more detail:
For each fragment you get in the fragment shader the interpolated height value of the current mesh. Depending on the height value you simply select the sample from the desired texture and put that color out.
|
69,652,171 | 69,652,207 | What does # operator do in C++ macros? | I came across this macro:
#define STR_ERROR(ecode) case ecode: return #ecode;
What does the #ecode part do?
ecode is an int, and this function returns a const char*.
I'm sure that this has been answered already, but my search-foo has abandoned me. ecode itself is specific to this code. Searching for c++ # gives generic information about macros (as well as some numbered lists relating to C++).
| According to cppreference:
# operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal
Example from Microsoft Docs
#include <stdio.h>
#define stringer( x ) printf_s( #x "\n" )
int main() {
stringer( In quotes in the printf function call );
stringer( "In quotes when printed to the screen" );
stringer( "This: \" prints an escaped double quote" );
}
Result:
In quotes in the printf function call
"In quotes when printed to the screen"
"This: \" prints an escaped double quote"
Google-Fu protip: I just searched for C++ macro #, the Google recommended adding operator at the end, and those docs were on the first page.
|
69,652,417 | 69,653,214 | Receive values from dynamic array | I recently asked question about how to work with element Edit1 dynamically, now I want to ask something about values, which I received from dynamical arrays. First I try to divide image into sectors:
const n=20;
unsigned short i, j, line_length, w = Image1->Width, h = Image1->Height, l = Left + Image1->Left, t = Top + Image1->Top;
unsigned short border = (Width-ClientWidth)/2, topborder = Height-ClientHeight-border;
Image1->Canvas->Pen->Color = clRed;
for (i = 0; i <= n; i++)
{
Image1->Canvas->MoveTo(0, 0);
line_length = w * tan(M_PI/2*i/n);
if (line_length <= h)
Image1->Canvas->LineTo(w, line_length);
else
{
line_length = h * tan(M_PI/2*(1-1.*i/n));
Image1->Canvas->LineTo(line_length, h);
}
}
Then I use regions to count black dots in each sector and I want to add values to element Memo:
HRGN region[n];
TPoint points[3];
points[0] = Point(l + border, t + topborder);
for (i = 0; i < n; i++)
{
for (j = 0; j <= 1; j++)
{
line_length = w * tan(M_PI/2*(i+j)/n);
if (line_length <= h)
points[j+1] = Point(l + border + w, t + topborder + line_length);
else
{
line_length = h * tan(M_PI/2*(1-1.*(i+j)/n));
points[j+1] = Point(l + border + line_length, t + topborder + h);
}
}
region[i] = CreatePolygonRgn(points, 3, ALTERNATE); // or WINDING ?? as u want
}
Byte k;
unsigned __int64 point_count[n] = {0}, points_count = 0;
for(j = 0; j < h; j++)
for (i = 0; i < w; i++)
if (Image1->Canvas->Pixels[i][j] == clBlack)
{
points_count++;
for (k = 0; k < n; k++)
if (PtInRegion(region[k], l + border + i, t + topborder + j))
point_count[k]++;
}
unsigned __int64 sum = 0;
for (i = 0; i < n; i++)
{
sum += point_count[i];
Memo1->Lines->Add(point_count[i]);
}
As i received an advice from one man, in order to allocate an array using a TEdit to specify the array's count I should use, for example DynamicArray:
#include <sysdyn.h>
DynamicArray<HRGN> region;
...
int n = Edit1-> Text.ToInt();
region.Length = n;
I have made the same changes to point_count array:
Byte k;
DynamicArray<unsigned __int64> point_count;
point_count.Length = n;
unsigned __int64 /*point_count[n] = {0},*/ points_count = 0;
...
The problem is that I received different values if I do it dynamically or statically(n=20).
Statically:
Dynamically:
|
The problem is that I received different values if I do it dynamically or statically(n=20)
There is no difference whatsoever in accessing elements of a static array vs a dynamic array. Your problem has to be elsewhere.
For instance, your static code is initializing all of the array elements to 0, but your dynamic code is not doing that, so they will have random values before your loop then increments them.
Try this:
DynamicArray<unsigned __int64> point_count;
point_count.Length = n;
for(int i = 0; i < n; ++i) {
point_count[i] = 0;
}
...
Alternatively:
DynamicArray<unsigned __int64> point_count;
point_count.Length = n;
ZeroMemory(&point_count[0], sizeof(unsigned __int64) * n);
...
Also, using the Image1->Canvas->Pixels[][] property is very slow. Consider using the Image1->Picture->Bitmap->ScanLine[] property instead for faster access to the raw pixels.
|
69,652,544 | 69,652,717 | When a template is instantiated? | The fact that a template is not instantiated until it is used so for example if I have this class template:
template <typename T>
struct Pow{
T operator()(T const& x) const{ return x * x; }
};
void func(Pow<double>); // Pow<double> instantiated here?
void func(Pow<int>){} // Pow<int> instantiated here?
int main(){
Pow<int> pi; // instantiated here?
func(pi); // Pow<int> instantiated here
}
So when exactly the template is instantiated?
So is Pow<int> instantiated when func(Pow<int>) is declared?
If I didn't use Pow<int> in main() then has it been instantiated because of its usage in func as the the type of its parameters?
| The general rule for implicit instantiation of class templates is as follows
[temp.inst]
2 Unless a class template specialization is a declared specialization, the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program. [...]
That in conjunction with this requirement about functions:
[dcl.fct.def.general] (emphasis mine)
2 In a function-definition, either void declarator ; or declarator ; shall be a well-formed function declaration as described in [dcl.fct]. A function shall be defined only in namespace or class scope. The type of a parameter or the return type for a function definition shall not be a (possibly cv-qualified) class type that is incomplete or abstract within the function body unless the function is deleted ([dcl.fct.def.delete]).
Tells us all we need to know to examine your program. Functions declarations don't require the class type to be complete. So...
Pow<double> instantiated here?
No. This is a function declaration that is not a definition. It does not require a complete class type for a parameter. Pow<double> is not implicitly instantiated.
Pow<int> instantiated here?
Yes. This is a function definition, and so an instantiation is required.
Pow<int> pi; // instantiated here?
Was already instantiated due to the function.
So when exactly the template is instantiated?
Strictly when required in a way that affects the semantics of the program.
So is Pow<int> instantiated when func(Pow<int>) is declared?
When func(Pow<int>) is defined.
If I didn't use Pow<int> in main() then has it been instantiated because of its usage in func as the the type of its parameters?
Yes, because you did so in a function definition.
|
69,652,744 | 69,652,829 | C++ Singleton private constructor not accessible from static function | I have a singleton class declaration here:
#ifndef GLFW_CONTEXT_H
#define GLFW_CONTEXT_H
#include <memory>
class GLFWContextSingleton
{
public:
static std::shared_ptr<GLFWContextSingleton> GetInstance();
~GLFWContextSingleton();
GLFWContextSingleton(const GLFWContextSingleton& other) = delete;
GLFWContextSingleton* operator=(const GLFWContextSingleton* other) = delete;
private:
GLFWContextSingleton();
};
#endif
and an implementation of the GetInstance function shown here
std::shared_ptr<GLFWContextSingleton> GLFWContextSingleton::GetInstance()
{
static std::weak_ptr<GLFWContextSingleton> weak_singleton_instance;
auto singleton_instance = weak_singleton_instance.lock();
if (singleton_instance == nullptr)
{
singleton_instance = std::make_shared<GLFWContextSingleton>();
weak_singleton_instance = singleton_instance;
}
return singleton_instance;
}
However the call to std::make_shared<GLFWContextSingleton>() gives me an error saying
‘GLFWContextSingleton::GLFWContextSingleton()’ is private within this context
I thought that this static method would have access to the private member functions. What is causing this and how do I fix it?
| The static function does have access to private members. make_shared does not.
make_shared is a template function that forwards the arguments it gets and calls the constructor of the specified class. So the call to the default constructor happens inside the make_shared function, not inside the GetInstance function, hence the error.
One way to deal with this is to use a private nested class as the only argument to the constructor.
#include <memory>
class GLFWContextSingleton
{
private:
struct PrivateTag {};
public:
static std::shared_ptr<GLFWContextSingleton> GetInstance();
~GLFWContextSingleton();
GLFWContextSingleton(const GLFWContextSingleton& other) = delete;
GLFWContextSingleton* operator=(const GLFWContextSingleton* other) = delete;
GLFWContextSingleton(PrivateTag);
};
std::shared_ptr<GLFWContextSingleton> GLFWContextSingleton::GetInstance()
{
static std::weak_ptr<GLFWContextSingleton> weak_singleton_instance;
auto singleton_instance = weak_singleton_instance.lock();
if (singleton_instance == nullptr)
{
singleton_instance = std::make_shared<GLFWContextSingleton>(PrivateTag{});
weak_singleton_instance = singleton_instance;
}
return singleton_instance;
}
int main() {
}
This way we keep the constructor public, but in order to use it we need a PrivateTag, only accessible to members of the class.
|
69,653,208 | 69,653,558 | If a function definition has a parameter of class template type and didn't use it (its members) then is it instantiated? | From the previous example I've posted here about when the template is instantiated?, I got the answer that only when a template is used the compiler instantiates it. But look at this example:
template <typename T>
struct Pow{
T operator()(T const& x){ return x * x; }
};
extern template struct Pow<int>; // explicit instantiation declaration
struct Foo{
Pow<int> pi{};
void fn(Pow<int>);
};
void Foo::fn(Pow<int> pw){
// std::cout << pw(7) << '\n';
}
void bar(Pow<int> pwi){
// std::cout << pwi(10) << '\n';
}
int main(){
Foo f;
}
As you can see I've declared an explicit template instantiation Pow<int> but haven't defined it. The program works just fine and doesn't complain about the missing definition of Pow<int>!
In the previous topic I've been answered if I use a template type as a type of parameter for a function definition (not declaration) then the template is instantiated but here as you can see: The member function Foo::fn(Pow<int>) and the ordinary function function bar(Pow<int>) are defined but the compiler doesn't complain about the definition of Pow<int>?!!!
The program fails to compile if I un-comment the lines in the aforementioned functions. so does it mean that Pow<int> is not instantiated when used as function parameter in the function definition and as member data like in Foo::Pow<int> pi{};?
I find it confusing:
void f(Pow<int>); // function declaration: Pow<int> is not instantiated yet.
void f2(Pow<int>){} // function definition: Pow<int> instantiated?
void f3(pow<int> Pwi){ std::cout << Pwi(10);} // function definition and usage of `Pow<int>`: Pow<int> instantiated?
In main:
Foo f; // f has pi of type Pow<int>. so Pow<int> is instantiated?
|
The program works just fine and doesn't complain about the missing definition of Pow<int>!
Because it isn't missing. Both forms of explicit instantiation (declaration and definition) cause the instantiation of class templates. An explicit instantiation definition causes the instantiation of member functions (which are normally instantiated lazily only when needed). On the other hand, an explicit instantiation declaration will suppress the implicit instantiation of a member function. Even if that member function body is visible!
It's a tool to write templates for a constrained set of types, while hiding their implementation. It allows one to do this:
//pow.h
template <typename T>
struct Pow{
T operator()(T const& x); // Just a declaration
};
extern template struct Pow<int>; // The class is instantiated, the member is
// assumed to be explicitly instantiated elsewhere
//pow.cpp
#include "pow.h"
template <typename T>
T Pow<T>::operator()(T const& x) { return x * x; }
template struct Pow<int>; // Explicit instantiation. The member function is defined
// in **this** translation unit.
And that is exactly why your program fails to link. The member operator() is never instantiated anywhere in your program. You can fix it by providing an explicit instantiation definition somewhere. For instance
template <typename T>
struct Pow{
T operator()(T const& x){ return x * x; }
};
// ...
int main() {
// ...
}
template struct Pow<int>; // Now the member function is emitted
Another use of this can be to potentially improve compile times. If you have a class template that you know is often instantiated for a specific set of types, you can help the linker along.
// my_string.h
template<typename charT>
class my_string {
// Everything, members and all
};
extern template class my_string<char>;
extern template class my_string<wchar_t>;
// my_string.cpp
#include <my_string.h>
// This file can be part of a shared object that ships with your library
// The common declarations are here
template class my_string<char>;
template class my_string<wchar_t>;
Now the linker doesn't have to sort the many duplicate symbols that would have been produced by implicit instantiation of the commonly used my_string<char> and my_string<wchar_t>.
|
69,653,849 | 69,654,056 | Mysterious C++ variadic template expansion | The following C++ function is extracted from lines 151 - 157 here:
template <typename... T>
std::string JoinPaths(T const&... paths) {
boost::filesystem::path result;
int unpack[]{0, (result = result / boost::filesystem::path(paths), 0)...};
static_cast<void>(unpack);
return result.string();
}
The function JoinPaths("foo", "bar", "doo.txt") will return a std::string with value "foo/bar/doo.txt" (I think) so I understand the semantics of the function.
I am trying to understand the two lines before the return statement. unpack in an array of ints, but what (and why) is happening with the leading 0's and the ellipses at the end. Can someone explain how this gets expanded? Why the 0's? I assume the static_cast is there to keep the compiler from optimizing away the array?
| int unpack[]{0, (result = result / boost::filesystem::path(paths), 0)...};
The first 0 is there to not try to create an empty array if someone calls the function with zero arguments.
(result = result / boost::filesystem::path(paths), 0)
This evaluates result = result / boost::filesystem::path(paths) and discards it. The result is the 0 to the right side of the comma.
... is a pack expansion, putting a , between each, making it into:
int unpack[]{0, (result = result / boost::filesystem::path("foo"),0),
(result = result / boost::filesystem::path("bar"),0),
(result = result / boost::filesystem::path("doo.txt"),0)
};
So, there will be four 0:s in unpack. The cast afterwards is just to disable the warning about the unused variable unpack.
Since C++17:
[[maybe_unused]] int unpack ... could be used instead to remove the warning. One could also use a fold expression and constexpr if to skip the unpack variable completely - and one could use std::filesystem instead of the boost::filesystem:
template<class... Ps>
std::string JoinPaths2(Ps&&... paths) {
std::filesystem::path result;
if constexpr (sizeof...(Ps)) // can't unfold empty expansion over /
result = (std::filesystem::path(std::forward<Ps>(paths)) / ...);
return result.string();
}
|
69,654,196 | 69,659,720 | Is it possible to control the Openmp thread that is used to execute an openmp task in C++? | Is it possible to control the openmp thread that is used to execute a particular task?
In other words say that we have the following three tasks:
#pragma omp parallel
#pragma omp single
{
#pragma omp task
block1();
#pragma omp task
block2();
#pragma omp task
block3();
}
Is it possible to control the set of openmp threads that the openmp scheduler chooses to execute each of these three tasks? The idea is that if I have used openmp's thread affinity mechanism to bind openmp threads to particular numa nodes, I want to make sure that each task is executed by the appropriate numa node core. Is this possible in Openmp 4.5? Is it possible in openmp 5.0?
| In a certain sense, this can be accomplished using the affinity clause that has been introduced with the OpenMP API version 5.0. What you can do is this:
float * a = ...
float * b = ...
float * c = ...
#pragma omp parallel
#pragma omp single
{
#pragma omp task affinity(a)
block1();
#pragma omp task affinity(b)
block2();
#pragma omp task affinity(c)
block3();
}
The OpenMP implementation would then determine where the data of a, b, and c has been allocated (so, in which NUMA domain of the system) and schedule the respective task for execution on a thread in that NUMA domain. Please note, that this is a mere hint to the OpenMP implementation and that it can ignore the affinity clause and still execute the on a different thread that is not close to the data.
Of course, you will have to use an OpenMP implementation that already supports the affinity clause and does more than simply ignore it.
Other than the above, there's no OpenMP conforming way to assign a specific task to a specific worker thread for execution.
|
69,654,338 | 69,654,437 | Read access violation when running my program | I am creating a simple Bank system in c++ to test my knowledge since I'm a beginner.
I am having trouble with writing data to a private class, and after looking around on the internet I came up with a solution that I thought would work but doesn't.
There is an exception thrown when I finish the "Creating a user" part which says "Exception thrown: read access violation._Pnext was 0x6". I'm not sure what this means, but my guess is that it has something to do with the pointers in the createuser function.
I hope I'm not too vague in my explanation here, but I have absolutely no idea what is happening. Also, any criticism is welcome.
#include <iostream>
#include <string>
void clearscreen();
int createuser();
class MyClass
{
private:
std::string Username;
std::string Password;
int money = 0;
public:
void setUsername(std::string x) {
Username = x;
}
void setPassword(std::string y) {
Password = y;
}
void setMoney(int z) {
money = z;
}
};
void clearscreen() {
system("cls");
}
int main() {
std::cout << "Welcome new User!\n" << std::endl;
bool exitprogram = false;
while (exitprogram == false)
{
std::cout << "The Options are:\n";
std::cout << "1. Create User\n" << "2. Login\n" << "3. Exit Program\n" << "\nEnter an option: ";
int option = 0;
std::cin >> option;
switch (option)
{
case 1:
createuser();
break;
case 2:
std::cout << "\nThis option is not avalible yet!";
case 3:
exitprogram = true;
break;
}
}
return 0;
}
int createuser() {
clearscreen();
MyClass User;
int* p = (int*)&User;
std::string* i = (std::string*)&User;
std::cout << "Please enter the correct information!\n" << "Username: ";
std::string createusern;
std::cin >> createusern;
*i = createusern;
std::cout << "\n Password: ";
std::string createpasswordn;
std::cin >> createpasswordn;
*i = createpasswordn;
std::cout << "\nDeposit Money: ";
int insertmoney;
std::cin >> insertmoney;
*p = insertmoney;
std::cout << "\n\n Congratz, You now have a bank accout! \n\n";
clearscreen();
return 0;
}
| Your pointer casting is all over the map and certainly "unusual" and incorrect for what you're trying to do.
This line *i = createusern; is incorrect because i is not pointing to a string. It is pointing to a User object. That you really want to do here is something like this
User.setUsername( createusern );
…and the same goes for your other population attempts. You have setter functions for these elements, so use them.
You should also keep in mind that your User object is local and will not survive past the end of the createuser function
|
69,654,724 | 69,655,422 | How do I read in a text file separated by spaces into an array in c++? | I have a text file of number called InputFile.txt. The file looks like this:
10.5 73.5 109.5 87 45 108 66 117 34.5 13.5 60 97.5 138 63 130.5 4.5 40.5 43.5 60 18
I want to read this file and insert each individual number as an element of the array arr. I know what I have does not attempt to add the elements to the array but I am not sure how I would even approach this. Any advice would be very appreciated.
int main(int argc, char* argv[]) {
float array[20];
ifstream file("InputFile.txt");
}
| I have given 2 solutions to this problem. The below program reads double from input.txt and if there is some invalid entry in the file lets say there is some string then it will skip that string and read the next value and only if that value is valid(double) it will put it into the array as you desire.
Solution 1: Using built in arrays
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::string line;
std::ifstream inFile("input.txt");
//in case of using array, size must be fixed and predetermined
double arr[20] = {0.0}; //you can choose size according to your needs
if(inFile)
{
double i = 0;//this variable will be used to add element into the array
int count = 0;
while(getline(inFile, line, '\n'))
{
std::istringstream s(line);
//take input(from s to i) and then checks stream's eof flag status
while(s >> i || !s.eof()) {
//check if either failbit or badbit is set
if(s.fail())
{
//clear the error state to allow further operations on s
s.clear();
std::string temp;
s >> temp;
continue;
}
else
{
arr[count] = i;
++count;
//break out of the loop so that we don't go out of bounds
if(count >= 20)
{
break;
}
}
}
}
}
else
{
std::cout<<"file could not be read"<<std::endl;
}
inFile.close();
for(double i: arr)
{
std::cout<<"elem: "<<i<<std::endl;
}
return 0;
}
The output of solution 1 can be checked here.
Solution 2: Using std::vector
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int main()
{
std::string line;;
std::ifstream inFile("input.txt");
std::vector<double> vec;
if(inFile)
{
double i = 0;//this variable will be used to add element into the vector
while(getline(inFile, line, '\n'))
{
std::istringstream s(line);
//take input(from s to i) and then checks stream's eof flag status
while(s >> i || !s.eof()) {
if(s.fail())
{
//clear the error state to allow further operations on s
s.clear();
std::string temp;
s >> temp;
continue;
}
else
{
vec.push_back(i);
}
}
}
}
else
{
std::cout<<"file could not be read"<<std::endl;
}
inFile.close();
for(double i: vec)
{
std::cout<<"elem: "<<i<<std::endl;
}
return 0;
}
The output of solution 2 can be seen here.
Both of these versions work even if there is an invalid input(like a string) in the input.txt file. As you can see here the input.txt file has strings in between numbers. The program just skips those invalid input and read the next thing. And if that next thing is double, it puts that thing/value into the vector/array.
Important Note
The advantage of using std::vector over built in array(in this case) is that you don't have know the size of the vector beforehand. So it is preferable because you don't know how many integers are there in the input.txt file. std::vector can handle this correctly/dynamically. But when using built in arrays you must know/specify the size of the array beforehand. This in turn means you must know beforehand how many integers are there in the input.txt, which is not practical.
|
69,654,793 | 69,655,875 | How to find line number in ThreadSanitizer stack trace | I compile using Clang with -g3 and -O1 flags, but TSan complains that it found a data-race and it outputs a totally obscure stack trace with no clear line numbers.
How to find line numbers in this case?
Output on Pastebin since Stack Overflow doesn't support more than 30k chars.
https://pastebin.com/raw/6izxznym
| Look for "/home" for finding your code.
The stacks of the threads look nice with well shown line numbers. Your MediaServer::initialize() created the thread T1.
Thread T1 (tid=2667937, running) created by main thread at:
#2 MediaServer::initialize /home/MediaServer/MediaServerMethods.cpp:1808
#3 main /home/MediaServer/MediaServer.cpp:33
T1 continued MediaServer initialization and created the thread 7.
Thread T7 (tid=2667963, running) created by thread T1 at:
#31 SimpleWeb::SocketServerBase<boost::asio::basic_stream_socket<boost::asio::ip::tcp, boost::asio::executor> >::start() /usr/local/include/simple-websocket-server/server_ws.hpp:437
#32 MediaServer::initialize()::$_7::operator()() const /home/MediaServer/MediaServerMethods.cpp:1812
T7 received some message and called your code, that was creating std::shared_ptr that was creating some std::string from a C string perhaps.
Previous write of size 8 at 0x7b1800006060 by thread T7:
#1 void std::__cxx11::basic_string<char>::_M_construct<char*>(char*, char*, std::forward_iterator_tag) /usr/include/c++/11/bits/basic_string.tcc:219
#2 rtc::impl::Certificate::Certificate()
...
#8 std::make_shared<rtc::PeerConnection>() /usr/include/c++/11/bits/shared_ptr.h:876
#9 RTCTransport::createPeerConnection() /home/MediaServer/MediaServerMethods.cpp:458
#10 MediaServer::initialize()::$_5::operator()(...) const /home/MediaServer/MediaServerMethods.cpp:1761
Finally thread T1 was attempting to construct the same std::string without using a lock guard.
WARNING: ThreadSanitizer: data race (pid=2667935)
Read of size 8 at 0x7b1800006060 by thread T1:
#1 void std::__cxx11::basic_string<char>::_M_construct<char*>(char*, char*, std::forward_iterator_tag) /usr/include/c++/11/bits/basic_string.tcc:225
#2 rtc::impl::Certificate::fingerprint[abi:cxx11]() const
...
#24 MediaServer::initialize()::$_7::operator()() const /home/MediaServer/MediaServerMethods.cpp:1812
|
69,654,900 | 69,667,187 | Is there any rule against putting more than one parameter in a mutator? | I need my mutator to call a different function in my constructor and another function anytime after that, so I was thinking of putting a bool as a second parameter to differentiate as follows:
void SetName(const char* name, bool init)
{
init ? this(name) : that(name);
}
Is this against convention or anything? Should I use two separate mutators instead?
| It allows you to make a mistake which can instead be prevented at compile-time. For example:
Example example;
example.SetName("abc", true); // called outside the constructor, `init == true` anyway
To prevent such situations, just replace your
struct Example {
Example() { SetName("abc", true); }
void SetName(const char* name, bool init) { init ? foo(name) : bar(name); }
};
with
struct Example {
Example() { foo("abc"); }
void SetName(const char* name) { bar(name); }
};
Testing:
Example example; // calls the for-the-constructor version
example.SetName("abc"); // calls the not-for-the-constructor version
example.SetName("abc", true); // obviously, doesn't compile any more
|
69,655,137 | 69,655,212 | How to contruct header file for class with struct define inside in C++ | If I have class that contains a struct in it. How do I declare that struct inside of a header file?
See example below. Is this the correct syntax?
context: my professor has a IList.h file that we have to implement in a LinkedList class. That's why there's inheritance syntax in my examples.
LinkedList.cpp
#include "LinkedList.h"
class LinkedList : public IList {
struct Node
{
int data;
struct Node *next;
}
};
LinkedList.h
#ifndef LINKED_LIST_
#define LINKED_LIST_
#include "IList.h"
class LinkedList: public IList
{
protected:
struct Node;
};
IList.h
// Modified from code created by Frank M. Carrano and Timothy M. Henry.
// Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.
#ifndef I_LIST_
#define I_LIST_
class IList
{
public:
/** Constructor */
IList () : traverseCount(0) { }
/** Destroys object and frees memory allocated by object.
(See C++ Interlude 2) */
virtual ~IList () { }
/** Gets the current number of entries in this list.
@return The integer number of entries currently in the list. */
virtual int getCurrentSize() const = 0;
/** Sees whether this list is empty.
@return True if the list is empty, or false if not. */
virtual bool isEmpty() const = 0;
/** Adds a new entry to this list.
@post If successful, newEntry is stored in the list and
the count of items in the list has increased by 1.
@param newEntry The object to be added as a new entry.
@return True if addition was successful, or false if not. */
virtual bool add(int newEntry) = 0;
/** Removes one occurrence of a given entry from this list,
if possible.
@post If successful, anEntry has been removed from the list
and the count of items in the list has decreased by 1.
@param anEntry The entry to be removed.
@return True if removal was successful, or false if not. */
virtual bool remove(int anEntry) = 0;
/** Removes all entries from this list.
@post List contains no items, and the count of items is 0. */
virtual void clear() = 0;
/** Tests whether this list contains a given entry.
@param anEntry The entry to locate.
@return True if list contains anEntry, or false otherwise. */
virtual bool contains(int anEntry) = 0;
/** Get the count of number of nodes traversed.
@return The integer number of nodes traversed since last time the count was reset. */
virtual int getTraverseCount() const { return traverseCount; }
/** Reset the count of nodes traversed to zero. */
virtual void resetTraverseCount() { traverseCount = 0; }
protected:
int traverseCount;
}; // end IList
#endif
| You'll need to redeclare at least the pure-virtual methods from IList in your LinkedList class, otherwise LinkedList will be an abstract class and so the compiler won't allow you to instantiate a LinkedList object:
// LinkedList.h
#ifndef LINKED_LIST_
#define LINKED_LIST_
#include "IList.h"
class LinkedList: public IList
{
public:
LinkedList();
virtual ~LinkedList();
virtual int getCurrentSize() const;
virtual bool isEmpty() const;
virtual bool add(int newEntry);
virtual bool remove(int anEntry);
virtual void clear();
virtual bool contains(int anEntry);
private:
struct Node
{
int data;
struct Node *next;
};
struct Node *first;
};
#endif
... then you'll need to write the actual code for your methods inside LinkedList.cpp:
// LinkedList.cpp
#include "LinkList.h"
LinkedList :: LinkedList()
{
[... code goes here...]
}
LinkedList :: ~LinkedList()
{
[... code goes here...]
}
int LinkedList :: getCurrentSize() const
{
[... code goes here...]
}
bool LinkedList :: isEmpty() const
{
[... code goes here...]
}
bool LinkedList :: add(int newEntry)
{
[... code goes here...]
}
bool LinkedList :: remove(int anEntry)
{
[... code goes here...]
}
void LinkedList :: clear()
{
[... code goes here...]
}
bool LinkedList :: contains(int anEntry)
{
[... code goes here...]
}
|
69,655,333 | 69,657,647 | Clunky movement on transformable objects SFML | So I am working on a game in SFML and am having a weird problem with movement. I have implemented a delta time so the movement speed is constant but I have this weird issue where I press a move key, the object jumps by speed units, pauses, then proceeds to move smoothly. I haven't been able to find much on this as I don't really know what problems I should be looking for. Here is a copy of my current code.
#include <SFML/Graphics.hpp>
#include "Player.h"
#include <iostream>
#include <vector>
void handleKeyPress(sf::Event &event, Player &player, float dt);
int main() {
sf::ContextSettings settings;
settings.antialiasingLevel = 16;
sf::RenderWindow window(sf::VideoMode(800, 600), "Title", sf::Style::Default, settings);
sf::Event event;
Player player;
player.setPosition(100, 100);
sf::Clock dtClock;
while (window.isOpen()) {
float dt = dtClock.getElapsedTime().asSeconds();
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
handleKeyPress(event, player, dt);
window.clear(sf::Color::Black);
//drawing happens hear
window.draw(player);
//end of frame
window.display();
dtClock.restart();
}
}
}
void handleKeyPress(sf::Event& event, Player& player, float dt) {
sf::Vector2f moveVector(0.0f, 0.0f);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
moveVector.x = -player.speed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
moveVector.x = player.speed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
moveVector.y = -player.speed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
moveVector.y = player.speed;
player.move(moveVector * dt);
}
Note that player is just an SFML Transformable object/drawable object.
| Your main is mixing event processing and state updates with drawing, which makes it hard to respect the fractional updates you intend to do with dt.
The code below undoes that: it first eats all events, then updates the game state, then draws.
In order to have smooth movement, you need to remember the Player velocity depending on which keys are pressed/released:
Add a velocity vector to Player
Change handleKeyPress to modify the velocity appropriately. Pay attention to multiple keypresses, eg up + right = (+1, +1)
Add an update method to player that adds a dt fraction of velocity to position.
Change it to:
while (window.isOpen()) {
float dt = dtClock.getElapsedTime().asSeconds();
// process events
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
} else if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased) {
// rewrite this to update player.velocity depending on what key is pressed if released
handleKeyPress(event, player, dt);
}
}
// apply dt * player.velocity to player.position
player.update(dt);
// draw
window.clear(sf::Color::Black);
//drawing happens hear
window.draw(player);
// restart the dtclock here, as display() will pause for a bit
dtClock.restart();
//end of frame
window.display();
}
|
69,655,477 | 69,689,950 | In Openmp is there a way to find out the place to which the master thread is assigned? | With openmp's thread affinity mechanisms, the master thread is assigned to the place where the parent of the master thread is running (where the set of places is specified by OMP_PLACES). It is my understanding that effectively this means that the OS determines the place where the master thread gets executed. Is there a way to find from inside your C++ code the actual place or hardware thread to which this master thread is binded? Thanks
| How about omp_get_place_num()?
The OpenMP specification states:
The omp_get_place_num routine returns the place number of the place to
which the encountering thread is bound.
Another possibility is to set the OMP_DISPLAY_AFFINITY environment variable to true which will cause the affinity information to be displayed.
|
69,655,884 | 69,655,987 | LinkedList class implementation cannot declare variable to be of Abstract Type | Where am I going wrong in constructing my LinkedList class?
I've re-declared the pure-virtual methods from IList in your LinkedList class, but LinkedList seems to be getting treated like an abstract class and so the compiler doesn't seem to allow me to create a LinkedList object in my main function:
main.cpp
#include <iostream>
#include <string>
#include "LinkedList.h"
using namespace std;
int main()
{
int A[] {1, 2, 3, 4, 5};
LinkedList l(A, 5);
cout << l.getCurrentSize()<<endl;
l.display();
return 0;
}
LinkedList.h
#ifndef LINKED_LIST_
#define LINKED_LIST_
#include "IList.h"
class LinkedList : public IList
{
protected:
struct Node
{
int data;
struct Node* next;
};
struct Node* first;
public:
// constructor
LinkedList() { first = nullptr; }
LinkedList(int A[], int n);
// accessors void display();
virtual int getCurrentSize();
//destructor
virtual ~LinkedList();
};
#endif
LinkedList.cpp
#include <iostream>
#include <string>
#include "LinkedList.h"
using namespace std;
// constructor
LinkedList::LinkedList(int A[], int n)
{
Node* last, * t;
int i = 0;
first = new Node;
first->data = A[0];
first->next = nullptr;
last = first;
for (i = 1; i < n; i++)
{
t = new Node;
t->data = A[i];
t->next = nullptr;
last->next = t;
last = t;
}
};
// destructor
LinkedList::~LinkedList()
{
Node* p = first;
while (first) {
first = first->next;
delete p;
p = first;
}
}
void LinkedList::display()
{
Node* p = first;
while (p)
{
cout << p->data >> " ";
p = p->next;
}
cout << endl;
}
int LinkedList::getCurrentSize() const
{
Node* p = first;
int len = 0;
while (p)
{
len++;
p = p->next;
}
return len;
}
IList.h
// Modified from code created by Frank M. Carrano and Timothy M. Henry.
// Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.
#ifndef I_LIST_
#define I_LIST_
class IList
{
public:
/** Constructor */
IList () : traverseCount(0) { }
/** Destroys object and frees memory allocated by object.
(See C++ Interlude 2) */
virtual ~IList () { }
/** Gets the current number of entries in this list.
@return The integer number of entries currently in the list. */
virtual int getCurrentSize() const = 0;
/** Sees whether this list is empty.
@return True if the list is empty, or false if not. */
virtual bool isEmpty() const = 0;
/** Adds a new entry to this list.
@post If successful, newEntry is stored in the list and
the count of items in the list has increased by 1.
@param newEntry The object to be added as a new entry.
@return True if addition was successful, or false if not. */
virtual bool add(int newEntry) = 0;
/** Removes one occurrence of a given entry from this list,
if possible.
@post If successful, anEntry has been removed from the list
and the count of items in the list has decreased by 1.
@param anEntry The entry to be removed.
@return True if removal was successful, or false if not. */
virtual bool remove(int anEntry) = 0;
/** Removes all entries from this list.
@post List contains no items, and the count of items is 0. */
virtual void clear() = 0;
/** Tests whether this list contains a given entry.
@param anEntry The entry to locate.
@return True if list contains anEntry, or false otherwise. */
virtual bool contains(int anEntry) = 0;
/** Get the count of number of nodes traversed.
@return The integer number of nodes traversed since last time the count was reset. */
virtual int getTraverseCount() const { return traverseCount; }
/** Reset the count of nodes traversed to zero. */
virtual void resetTraverseCount() { traverseCount = 0; }
protected:
int traverseCount;
}; // end IList
#endif
| Your IList is an abstract class with six pure virtual member functions. In order to create the instance of the derived one (i.e. LinkedList) you need to implement those functions inside the child as well.
class LinkedList : public IList
{
// ..... other members
public:
// ..... other members
virtual int getCurrentSize() const override;
bool isEmpty() const override { // implementation }
bool add(int newEntry) override {// implementation }
bool remove(int anEntry) override { // implementation }
bool contains(int anEntry) override { // implementation }
void clear() override { // implementation}
};
Also recommended using the override specifier to override the virtual functions from the base class, so that both the compiler and the reader can easily recognize them, without looking into to the base.
Other Issues:
Also note that your getCurrentSize() functions declaration in the child class (i.e. LinkedList) lacks a const.
Typo at cout << p -> data >> " "; should be cout << p->data << " ";
Why is "using namespace std;" considered bad practice?
|
69,655,949 | 69,660,821 | Load images in QLabel | How to show more number(folder) of images in Qlabel or QScrollArea?
QImage image("E:/Raul/Images");
ui.label->setPixmap(QPixmap::fromImage(image));
Like this but i want more number images will load in one label.
| Result:
Code:
#include <QApplication>
#include <QLabel>
#include <QLineEdit>
#include <QPointer>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWizardPage>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget widget;
QVBoxLayout *layout=new QVBoxLayout();
QLabel *label=new QLabel("<img src=:/0_0.jpg align=middle><img src=:/0_1.jpg align=middle><strong>Hello</strong> "
"<font color=red>Sai Raul!");
layout->addWidget(label);
widget.setLayout(layout);
widget.show();
return a.exec();
//
}
QLabel is not a web browser, therefore hyperlinks like <img src=/media/cc0-images/grapefruit-slice-332-332.jpg/> doesn't work, but why images from resources can not do it))).
|
69,656,454 | 69,691,861 | Check for end-of-list in boost::intrusive::list without container? | I'm getting started with Boost.Intrusive, specifically interested in the doubly-linked list (boost::intrusive::list).
This would be trivial to do in a "hand-rolled" linked list, but so far I can't find a Boost equivalent:
Given a node that belongs to a list, how do I check to see if it represents the end of the list, without needing the owning container.
In a hand-made list, this would be as simple as checking if the "next" pointer is NULL.
With boost::intrusive::list, there is the s_iterator_to function, which converts a plain node to an iterator. And you can check that against mylist.end(), which gives the desired result, but it requires a reference to the list container itself.
I also note that using operator++ on such an iterator simply produces a garbage value once it is moved past the end — no error or assert from Boost.
| After some more research and thought, it seems that there is no way to do what I want with the standard boost::intrusive::list functionality.
The list provided is, in fact, a circular linked list, not a linear one. So, there is no "null pointer" at the end.
The implementation seems to follow a similar design to the Linux kernel's list.h. You always need a reference to the container object because that contains the "head" of the circular list, which is a special node containing no user data. This is also the node that represents end() during traversal.
As to why this design is chosen, I haven't found any hard evidence. Seemingly, the circular list design allows a simpler implementation, with fewer branches. See, for example, this old article, which says "The circular nature of the list makes inserting and removing nodes simple and branch free."
I am not fully convinced by that, since I think using "pointer-to-pointer" style handling can avoid the branches, too. But that's how it's done in boost::intrusive::list, regardless.
|
69,656,682 | 69,658,539 | Using ESP_NOW with loop and delays | I'm trying to receive a data from one esp32 to another.
I'm also doing some looping with delays for reading a sensor data and switch on/off relay cooling.
This device also use ESPAsyncWebServer as API server (not included in code for the size).
I'm receiving the data from one eps32 in POST request to API right now. I would like to change this as to be able to recieve with esp_now. I was doing some experiments, but the data receving is delayed because of delay method in loop.
Is there a way to make this asynchronized as for example the ESPA above?
I also tried a way with comparing a milis() (time) to wait for a loop, but I thing that is too "resource consuming" task, to let it compare in full speed in loop like a vortex forever.
here is my loop
it's just a simple loop with some vars and delay function for example
void loop() {
if (WiFi.status() == WL_CONNECTED) {
float temp_check = dht.readTemperature();
if (temp_check == 0) {
delay(1000);
temp_check = dht.readTemperature();
}
if (temp_check > 32.0 && *cooling_switch_p == false) {
Serial.println("[ INF ] Too high temperature, switch on a cooling system");
digitalWrite(COOLING_RELAY, LOW);
*cooling_switch_p = true;
}
else if (temp_check < 30.0 && *cooling_switch_p == true) {
Serial.println("[ INF ] Normal temperature, switch off a cooling system");
digitalWrite(COOLING_RELAY, HIGH);
*cooling_switch_p = false;
}
Serial.print("[ DBG ] Light Switch: ");
Serial.println(String(light_switch));
Serial.println("");
Serial.print("[ DBG ] Pump Switch: ");
Serial.println(String(pump_switch));
Serial.println("");
delay(5000);
}
else {
Serial.println("[ ERR ] Wifi not connected. Exiting program");
delay(9999);
exit(0);
}
}
| I assume you're trying to send your sensor data from this device to another one while more or less accurately maintaining the 5-second sampling interval. You can create a simple asynchronous architecture yourself using 2 threads.
The existing thread (created by Arduino) runs your current loop() which reads the sensor every 5 seconds. You add a second thread which deals with transmitting the sample to other devices. The first thread posts the sample to the second thread through a FreeRTOS queue; second thread immediately goes to work transmitting. The first thread continues to mind its own business without waiting for transmission to complete.
Using the FreeRTOS documentation on creating tasks and queues:
#include <task.h>
#include <queue.h>
#include <assert.h>
TaskHandle_t hTxTask;
QueueHandle_t hTxQueue;
constexpr size_t TX_QUEUE_LEN = 10;
// The task which transmits temperature samples to wherever needed
void txTask(void* parm) {
while (true) {
float temp;
// Block until a sample is posted to queue
const BaseType_t res = xQueueReceive(hTxQueue, static_cast<void*>(&temp), portMAX_DELAY);
assert(res);
// Here you write your code to send the temperature to other device
// e.g.: esp_now_send(temp);
}
}
void setup() {
// Create the queue
hTxQueue = xQueueCreate(TX_QUEUE_LEN, sizeof(float));
assert(hTxQueue);
// Create and start the TX task
const BaseType_t res = xTaskCreate(txTask, "TX task", 8192, nullptr, tskIDLE_PRIORITY, &hTxTask);
assert(res);
// ... rest of your setup()
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
float temp_check = dht.readTemperature();
// Post fresh sample to queue
const BaseType_t res = xQueueSendToBack(hTxQueue, &temp_check, 0);
if (!res) {
Serial.println("Error: TX queue full!");
}
// ... Rest of your loop code
}
}
|
69,657,686 | 69,658,058 | Running thread periodically every 20 ms fails | currently i am programming for an embedded application which reads values from sensors periodically. I want them to be read, every 20 ms.
Im using this tutorial
struct periodic_info {
int sig;
sigset_t alarm_sig;
};
static int make_periodic(int unsigned period, struct periodic_info *info)
{
static int next_sig;
int ret;
unsigned int ns;
unsigned int sec;
struct sigevent sigev;
timer_t timer_id;
struct itimerspec itval;
/* Initialise next_sig first time through. We can't use static
initialisation because SIGRTMIN is a function call, not a constant */
if (next_sig == 0)
next_sig = SIGRTMIN;
/* Check that we have not run out of signals */
if (next_sig > SIGRTMAX)
return -1;
info->sig = next_sig;
next_sig++;
/* Create the signal mask that will be used in wait_period */
sigemptyset(&(info->alarm_sig));
sigaddset(&(info->alarm_sig), info->sig);
/* Create a timer that will generate the signal we have chosen */
sigev.sigev_notify = SIGEV_SIGNAL;
sigev.sigev_signo = info->sig;
sigev.sigev_value.sival_ptr = (void *)&timer_id;
ret = timer_create(CLOCK_MONOTONIC, &sigev, &timer_id);
if (ret == -1)
return ret;
/* Make the timer periodic */
sec = period / 1000000;
ns = (period - (sec * 1000000)) * 1000;
itval.it_interval.tv_sec = sec;
itval.it_interval.tv_nsec = ns;
itval.it_value.tv_sec = sec;
itval.it_value.tv_nsec = ns;
ret = timer_settime(timer_id, 0, &itval, NULL);
return ret;
}
static void wait_period(struct periodic_info *info)
{
int sig;
sigwait(&(info->alarm_sig), &sig);
}
static int thread_1_count;
The Main:
int main(){
pthread_t t_1;
pthread_t t_2;
sigset_t alarm_sig;
int i;
printf("Periodic threads using POSIX timers\n");
/* Block all real time signals so they can be used for the timers.
Note: this has to be done in main() before any threads are created
so they all inherit the same mask. Doing it later is subject to
race conditions */
sigemptyset(&alarm_sig);
for (i = SIGRTMIN; i <= SIGRTMAX; i++)
sigaddset(&alarm_sig, i);
sigprocmask(SIG_BLOCK, &alarm_sig, NULL);
pthread_create(&t_1, NULL, thread_1, NULL);
sleep(10);
printf("Thread 1 %d iterations\n", thread_1_count);
return 0;
My Problem now, i measured the time with high resolution clock with a period of 20ms.
static void *thread_1(void *arg)
{
struct periodic_info info;
printf("Thread 1 period 10ms\n");
make_periodic(20000, &info);
while (1) {
auto start = std::chrono::high_resolution_clock::now();
printf("Hello\n");
thread_1_count++;
wait_period(&info);
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> ms_double = finish - start;
std::cout << ms_double.count() << "ms\n";
}
return NULL;
}
The output i get ist:
...
19.8556ms
19.8587ms
19.8556ms
19.8543ms
19.8562ms
19.8809ms
19.7592ms
19.8381ms
19.8302ms
19.8437ms
...
So my Question, why is the Time shorter than my Period time, what am i doing wrong ?
| To be more accurate, don't take time twice on each iteration, keep the last value, like this:
static void *thread_1(void *arg)
{
struct periodic_info info;
printf("Thread 1 period 10ms\n");
make_periodic(20000, &info);
auto start = std::chrono::high_resolution_clock::now();
while (1) {
wait_period(&info);
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> ms_double = finish - start;
std::cout << ms_double.count() << "ms\n";
start = finish;
}
return NULL;
}
This way, it will make the time measuring more accurate.
|
69,657,816 | 69,658,099 | C++ difference between passing argument from a function call or passing argument from variable | Whats the difference between this:
function1(function2());
And this:
var1 = function2();
function1(var1);
In terms of efficiency or whatever, what is the best option?
| Before C++11 there is no big difference. Since move semantics were introduced the difference can be substantial. For example when a function needs to make a copy of its parameter it can have two overloads: one that actually does make a copy and another one that can move when the parameter is a temporary:
#include <iostream>
struct bar {};
bar b() { return {};}
struct foo {
bar b;
void set(const bar& in) {
std::cout << "copy \n";
b = in;
}
void set(bar&& in){
std::cout << "no need to copy, can move\n";
b = std::move(in);
}
};
int main() {
foo f;
bar b1;
f.set(b1);
f.set(b());
}
bar in this example is just a lightweight class, but when it is cheap to move but expensive to copy then f.set(b1) is less efficient than f.set(b()). The caller could f.set(std::move(b1)), but it is more clear to call f.set(b()) rather than having a moved from object hanging around.
However, already before C++11, the question you should actually ask is: Does it make sense to give a name to the result of calling function2? Do you need the result only to call function1 or do you need it also elsewhere? And this can be answered independently of whether you are writing ancient C++ or whether move semantics are involved. In short: Write code to be clear and readable. Concerns about efficieny are for a later stage, when you have correct and working code that you can measure and profile.
|
69,658,500 | 69,663,906 | Using destructor to finish a task | I am currently experimenting with the following approach to finalize processing some data (pseudo-code).
void run_processing(container datas)
{
// runs some conversion on data and sends it somewhere.
}
struct process_item
{
container datas;
process_item(const char* data)
{
datas.add(data);
}
~process_item()
{
run_processing(datas);
}
operator <<(const char* data)
{
datas.add(data);
}
}
process_item create_item(const char* data)
{
process_item item(data);
// Possible additional calls to setup item.
return item;
}
In my tests this allows for a call.
create_item("my_data") << "additional data" << "even more data";
// Once this piece executes the destructor for process_item is assumed to be called.
The pseudo code doesn't really show the intended benefits but that is besides my question.
I am trying this because I have some restrictions; The processing can't start until all data has been input, and it is not known when that's the case other than when the scope of process_item has ended. For simplicities sake, assume I can't call an additional method or add a flag after the last data is added.
Can the destructor be assumed to be called at the expected time, or is this too risky having the option to differ depending on optimization level and compiler?
Clarification
"At the right time" meaning before the next line, the one after the call to create_item executed.
| A problem with your strategy is that at destruction time, you have no (safe) ability to
Throw an exception to report an error, or
Return a result
Throwing exceptions from destructor is a really, really bad idea, because destructors are run during stack unwinding if someone else throws an exception, and if you throw an exception during stack unwinding, your program is terminated.
There are ways around it, but they involve ... not throwing an exception during stack unwinding. So any error is lost.
Also, you run into the possibility that an exception causes the action you intend to do to be partially prepared, then executed. This can ruin the coherence of your data.
One approach to deal with this is:
[[nodiscard]] process_item& operator <<(const char* data)
{
datas.add(data);
return *this;
}
then provide an operator error_code() or whatever to force the user to assign the entire << chain to an error variable. Is is that operator error_code() that causes the code to be executed.
Under this model, an exception thrown on the line of << doesn't cause the operation to run, because the operator error_code() is skipped.
Sadly, [[nodiscard]] isn't c++11.
...
Other than that, yes, temporary objects are destroyed at the end of the full expression they are created in. There are a few exceptions involving elision and argument passing, but those are unlikely to apply in code like you describe.
As you have written a destructor, you need to obey the rule of 5. This means you need to delete or implement a copy/move assign/constructor (delete is the easy option).
If you delete copy/move operations, you may run into problems in create_item, as NRVO elision is not guaranteed. It will work in c++17 if you use RVO elision (as that is now guaranteed). Another option is to make your class move-friendly (including moving the "prepared to execute" state) so that a moved-from instance doesn't run the operation.
I strongly suggest you block copy operations. It would be rather easy to accidentally make 3 copies of some operation you want to run once. It is cool to be able to copy an operation half way through, but the C++ copy semantics are a bit too easy to engage: if you want to be able to copy, but not have it happen accidentally, add a .copy()const method that returns a prvalue.
|
69,658,562 | 69,684,417 | What algorithm meets the complexity requirements of the C++ `std::stable_sort`? | The docs from www.cppreference.com says that the complexity of std::stable_sort() is
O(n * log(n)^2) [...]. If additional memory is available, then the complexity is O(n * log(n)).
What algorithm would meet this requirement, and how much is the specified "additional memory"?
| According to the commenters on the question and some further reading, the complexity is specified as such because there is no trivial stable in-place O(nlogn) sorting algorithm. With some further inspection on the source code, the implementation of libc++ and libstdc++ are similar, both are a merge sort where the in-place merge has complexity O(nlogn). As for the "additional memory", the two libraries require N additional memory, where N is the length of the array.
More specifically, instead linearly scanning the two sub-arrays and merging one element at a time, the in-place merge search for a way partition each of the two sub-arrays into two parts (four parts in total), such that when swapping the middle two parts, all elements in the the leftmost two parts are smaller or equal to the rightmost two parts. Then they perform in-place merge on the leftmost and rightmost two part respectively.
|
69,659,009 | 69,660,162 | Storing an variant of references for a view type in C++ | I have an environment where I have no C++17 (C++14 ATM) features nor boost.
Currently I have a class responsible for sending messages between services in our domain, this class uses multiple types of addressing (both types are non trivial) and one of them can be converted to other (lets say A can be converted to B).
Class that is responsible for sending messages, contains of multiple (templated, because messages have no base class) methods, duplicated for both of the addressing types using function overload.
class Sender{
public:
// old API
template<typename TReq>
send(const A&target, TReq req){send(target, make_request{req});}
// old API
template<typename TReq>
send(const B&target, TReq req){sendB(target, make_request{req});}
protected:
// done for mocking/testing purpose only
virtual send(const A&target, MessageProxy message);
virtual sendB(const A&target, MessageProxy message);
};
Addressing A and B is done interchangeable by the users (they don't care if this is A or B type of address) In order to play nice with google mock I need to provide different names for overloaded methods (I could do this in mock, but decided to call them differently here, there is no difference)
The problem that I want to solve is simple. Provide a single virtual send method, that will take an "union" of references to address type A or B (think of it as variant<A&, B&>) that can be used the same way as templated versions of those methods, like.
virtual send(const TargetProxy &target, MessageProxy message);
that can be used
EXPECT_CALL(mock, send(Eq(A{}), Message{}))...
EXPECT_CALL(mock, send(Eq(B{}), OtherMessage{}))...
The type that carry A& or B& (TargetProxy) should hold an const Reference to A OR to B and should be used only to pass A or B from templated send to virtual send, but I failed to figure out a simple solution for this
| There are lots of boilerplate missing, but PoC might be sth like this:
#include <utility>
#include <cassert>
#include <iostream>
struct A {};
struct B {};
struct EitherRef : private std::pair<A*, B*>
{
EitherRef(A& a)
: std::pair<A*, B*>(std::addressof(a), nullptr){};
EitherRef(B& b)
: std::pair<A*, B*>(nullptr, std::addressof(b)){};
bool hasA() const {return this->first!=nullptr;}
bool hasB() const {return this->second;}
operator A&() { assert (this->first);return *this->first; }
operator B&() { assert (this->second);return *this->second; }
};
template <typename Func>
void applyVisitor(EitherRef e, Func f)
{
if (e.hasA()) {
f(static_cast<A&>(e));
} else if (e.hasB()) {
f(static_cast<B&>(e));
}
}
void f(const EitherRef& r)
{
struct {
void operator()(A&) {
std::cout <<"A\n";
}
void operator()(B&) {
std::cout <<"B\n";
}
} v;
applyVisitor(r, v);
}
int main(int, char*[])
{
A a1;
B b1;
EitherRef ra{a1};
EitherRef rb{b1};
f(ra);
f(rb);
return 0;
}
|
69,659,326 | 69,677,144 | initialize a vector by a pointer of a CLASS | I am trying to initialize a vector of pointers of a class UNITCallback.
Here is the code:
file vector.h
#include <memory>
#include <unistd.h>
class UNITEvent_Loop;
class UNITCallback
{
public:
UNITCallback();
virtual ~UNITCallback();
virtual const fd_set & FdSet() = 0;
virtual void operator()(const fd_set & fds) = 0;
virtual void operator()() = 0;
virtual void eventLoop(UNITEvent_Loop * ev);
virtual UNITEvent_Loop * eventLoop();
private:
UNITEvent_Loop * evt_loop_;
};
class UNITEvent_Loop
{
public:
enum priority { LOW , HIGH};
UNITEvent_Loop();
~UNITEvent_Loop();
void stopLoop();
void runLoop();
void runLoop(int timeout); // in milliseconds
void runLoop(struct timeval * TO);
private:
UNITEvent_Loop & operator =(const UNITEvent_Loop &);
UNITEvent_Loop(const UNITEvent_Loop &);
std::auto_ptr<struct CMSPEvent_LoopImpl> impl_;
};
file vector.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include"vector.h"
struct UNITEvent_LoopImpl
{
UNITEvent_LoopImpl() :
stopLoop(false),
callBacks(1024,0),//(FD_SETSIZE, 0),
priorities(FD_SETSIZE, UNITEvent_Loop::LOW) {};
//CMSPMutex protect;
bool stopLoop;
std::vector<UNITCallback * > callBacks;
std::vector<UNITEvent_Loop::priority> priorities;
};
int main() {
return 0;
}
so when I compile I receive:
/usr/include/c++/8/bits/stl_vector.h: In instantiation of ‘void
std::vector<_Tp, _Alloc>::_M_initialize_dispatch(_Integer, _Integer,
std::__true_type) [with _Integer = int; _Tp = UNITCallback*; _Alloc =
std::allocator<UNITCallback*>]’:
/usr/include/c++/8/bits/stl_vector.h:555:4: required from
‘std::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator,
const allocator_type&) [with _InputIterator = int; _Tp =
UNITCallback*; _Alloc = std::allocator<UNITCallback*>;
std::vector<_Tp, _Alloc>::allocator_type =
std::allocator<UNITCallback*>]’
/vector/src/vector.cpp:20:48: required
from here /usr/include/c++/8/bits/stl_vector.h:1426:52: error: invalid
conversion from ‘int’ to ‘std::vector<UNITCallback*>::value_type’ {aka
‘UNITCallback*’} [-fpermissive]
_M_fill_initialize(static_cast<size_type>(__n), __value);
^~~~~~~
it looks like I can't initialize well. why?
EDIT:
I will add the cmake file
cmake_minimum_required(VERSION 3.11.4)
cmake_policy (VERSION 3.11.4)
project (MSG_IMPF CXX C Fortran)
set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_STANDARD 98)
SET(GCC_COVERAGE_COMPILE_FLAGS "-g -fpic -shared")
#at moment missing -lnsl -lsocket
SET(GCC_COVERAGE_LINK_FLAGS "-lrt -lpthread")
#Appending to corresponding CMake variables:
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
add_definitions(-D_POSIX_PTHREAD_SEMANTICS -D_POSIX_C_SOURCE=199506L -D__EXTENSIONS__ -DIT_USE_STD_IOSTREAM)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_SKIP_RPATH ON)
get_filename_component(LOCATION ${CMAKE_SOURCE_DIR} PATH)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LOCATION}/lib64)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${LOCATION}/lib64)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${LOCATION}/bin)
include_directories(
${LOCATION}/src
)
add_executable(test1
vector.cpp
)
so the verbose is:
/usr/bin/c++ -DIT_USE_STD_IOSTREAM -D_POSIX_C_SOURCE=199506L -D_POSIX_PTHREAD_SEMANTICS -D__EXTENSIONS__ -I/vector/src -g -fpic -shared -std=gnu++98 -o CMakeFiles/test1.dir/vector.cpp.o -c /vector/src/vector.cpp
| I found the solution, I did a casting to (UNITCallback*) and it worked like a charm.
here is the code:
#include <iostream>
#include <vector>
#include <algorithm>
#include"vector.h"
struct UNITEvent_LoopImpl
{
UNITEvent_LoopImpl() :
stopLoop(false),
callBacks(1024,(UNITCallback*)0),//(FD_SETSIZE, 0),
priorities(FD_SETSIZE, UNITEvent_Loop::LOW) {};
//CMSPMutex protect;
bool stopLoop;
std::vector<UNITCallback * > callBacks;
std::vector<UNITEvent_Loop::priority> priorities;
};
int main() {
return 0;
}
|
69,659,434 | 69,700,603 | Template argument deduction when mixing variadic template with C-style variadic function | Inspired by this answer, I produced this code whose output depends on the compiler:
template <typename... Args>
constexpr auto foo(Args&& ...args, ...) noexcept {
return sizeof...(args);
}
constexpr auto bar() noexcept {
return (&foo<int>)(1, 2);
}
If compiled with GCC 11, bar calls foo<int> and returns 1, while both clang 13 and MSVC 2019 deduce foo<int, int> and bar returns 2.
This is my sandbox on godbolt: https://godbolt.org/z/MedvvbzqG.
Which output is correct?
EDIT:
The misbehavior persists if I use return foo<int>(1, 2); directly, i.e. with
constexpr auto bar() noexcept {
return foo<int>(1, 2);
}
Sandbox updated: https://godbolt.org/z/Wj757sc7b.
| Edit: after the question was edited, it now comprises two orthogonal sub-questions, which I've handled separately.
Given foo<int>(1, 2), should the parameter pack be deduced to cover all args?
Yes. The parameter pack does occur at the end of the parameter-declaration-list, which is the criterion for whether it's non-deduced or not. This was actually clarified in CWG issue 1569. We can convince ourselves by observing that all compilers agree this is fine:
template <typename... Args>
constexpr auto foo(Args&& ...args, ...) noexcept {
return sizeof...(args);
}
static_assert(2 == foo(1, 2), "always true");
Only when we change foo to foo<int>, GCC suddenly stops deducing the pack. There's no reason for it to do so, explicitly supplying template arguments to a pack should not affect whether it's eligible for deduction.
Do calls of the form (&T<...>)(...) still invoke template argument deduction?
The answer is yes, as discussed in the open CWG issue 1038:
A related question concerns an example like
struct S {
static void g(int*) {}
static void g(long) {}
} s;
void foo() {
(&s.g)(0L);
}
Because the address occurs in a call context and not in one of the contexts mentioned in 12.3 [over.over] paragraph 1, the call expression in foo is presumably ill-formed. Contrast this with the similar example
void g1(int*) {}
void g1(long) {}
void foo1() {
(&g1)(0L);
}
This call presumably is well-formed because 12.2.2.2 [over.match.call] applies to “the address of a set of overloaded
functions.” (This was clearer in the wording prior to the resolution
of issue 704: “...in this context using &F behaves the same as using
the name F by itself.”) It's not clear that there's any reason to
treat these two cases differently.
As the note explains, prior to issue 704 we had this very explicit section:
The fourth case arises from a postfix-expression of the form &F, where F names a set of overloaded functions. In the
context of a function call, &F is treated the same as the name F by itself. Thus, (&F)( expression-listopt ) is simply
F( expression-listopt ), which is discussed in 13.3.1.1.1.
The reason this wording ended up being removed is not that it was defective, but that the entire section was poorly worded. The new wording still explicitly states that overload resolution is applied to an address of an overloaded set (which is what we have here):
If the postfix-expression denotes the address of a set of overloaded functions and/or function templates, overload resolution is applied using that set as described above.
|
69,660,033 | 73,834,148 | Is it possible to only link a project without compiling when using visual studio 2019? | In my project, there is a common header file shared by many source files. Usually, a modification of the header only affects several source files. I want to recompile those files manually and then let vs to link the project.
| Sure, compile your C++ files only (ctrl-F7). Then link the project (right click project, then "Project only" -> Link), then run. In Options => Build And Run, make sure you specify "Prompt to build" when projects are out of date, and then choose to run instead of build. Good luck!
|
69,660,173 | 69,660,525 | Return iterator for c type arrays? | In the MRE https://godbolt.org/z/jdjPzdGeo, is there a way to return an iterator for c type arrays in Func like what you see with std::array in Func2 and Func3? IDK what the return type would be.
Also, is there a way to make Func constexpr like in Func2?
Edit:
Add the code here
#include <array>
std::pair<int*, std::size_t>
Func() noexcept
{
// why does constexpr instead of static not work?
static int arr[] = {1, 2};
return { arr, std::size(arr) };
}
constexpr std::pair<std::array<int,2>::const_iterator, std::array<int,2>::const_iterator>
Func2() noexcept
{
constexpr std::array<int, 2> arr {{1, 2}};
return { std::cbegin(arr), std::cend(arr) };
}
std::pair<std::array<int,2>::const_iterator, std::array<int,2>::const_iterator>
Func3() noexcept
{
static std::array<int, 2> arr {{1, 2}};
return { std::cbegin(arr), std::cend(arr) };
}
int main()
{
Func();
Func2();
Func3();
}
|
Return iterator for c type arrays?
IDK what the return type would be.
The iterator type for arrays is a pointer. for example, if you have an array of int, then the iterator type for the array is int*.
and am expecting the return type to be an iterator of some sort.
int* is an iterator.
int* works for std::begin but what about std::cbegin?
If you want a constant iterator, that would be const int*.
Your Func2 returns dangling iterators as far as I can tell. Don't return iterators, references etc. to objects with automatic storage duration.
|
69,660,858 | 69,661,903 | QString Resets after appending 10 characters | I just started QT Language. A strange error occurred when I tried appending a character 10 times to it. It resets and starts over. Does anyone know a solution?
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<string>
#include<iostream>
// First Number / Second Number
double num1, num2;
// Action s-substract a-add n-none
char act;
// Result
double result;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_16_clicked()
{
// Test Button
AppendToLabel(2);
}
QString tempLabel = "0";
void MainWindow::AppendToLabel(int s){
//QString LabelText = ui->displayText->text();
//testCase
QString LabelText = tempLabel;
// Updates the label acording to the button
if(tempLabel.toInt() == 0)
{
// If the Number 0 present in the label - Rplace it
LabelText = QString::number(s);
}
else
{
// If not not - Append it to the label
LabelText.append(QString::number(s));
}
double apendedNumber = LabelText.toDouble();
qDebug() << LabelText;
tempLabel = LabelText;
//ui->displayText->setText(LabelText);
}
When I append the 11th character, it replaces the whole string instead of appending it to the existing one.
I Updated the question with the full code. that needs to reproduce the error. When I pressed the Button 10 times, It correctly appends to the label as "2222222222". But as soon as I pressed the 11 time, it replaces as "2".
| A 32-bit integer value can have a maximum value of 2^31 - 1, or 2147483647, which happens to be 10 digits long. So an 11 digit number would fail when calling toInt().
QString s = "12345678901"
qDebug() << s.toInt(); // prints '0'
|
69,660,887 | 69,667,881 | UWP TabView change tab programatically | How can I change TabView's tab programatically? For example user have 2'nd tab opened and I want to change tab to the first one.
| In C++ you have to do it as following:
int index = 1;
if (tabcontrol->TabItems->Size > index)
{
tabcontrol->SelectedIndex = index;
}
|
69,661,158 | 69,661,460 | Define a macro which defines a pow function only in the case where the exponent is an integer | Following a profiling of my C++ code, it appears that the pow function is used a lot.
Some of my pow functions have an integer exponent and another non-integer exponent. I am only interested for the ones with integer exponent.
To gain in performance, I am looking a way to define a macro like this:
#define pow(x,n) ({\
double product;\
if (typeid(n).name() == "i") {\
for(int i = 0; i < n-1; i++)\
product *= x;}\
else\
product = pow(x,n);\
product;\
})
But I don't get the gain expected regarding the runtime. I think this is due to the else part in my macro where I call the classical pow function.
How can I determine in advance the type of exponent before macro was "written" during the pre-processing?
Ideally, I would like this macro only to be applied if the exponent is an integer, but it seems my attempt is not pertinent.
From your suggestions, I tried three options:
First option: Just add overload inline functions with base which is integer or double:
// First option
inline int pow(int x, int n){
// using simple mechanism for repeated multiplication
int product = 1;
for(int i = 0; i < n; i++){
product *= x;
}
return product;
}
inline int pow(double x, int n){
// using simple mechanism for repeated multiplication
double product = 1;
for(int i = 0; i < n; i++){
product *= x;
}
return product;
}
Result: runtime = 1 min 08 sec
Second option: Define a macro that calls via inline my_pow function if the exponent n is not an integer:
// Second option
inline double my_pow(double x, double n){
return pow(x,n);
}
#define pow(x,n) ({\
double product = 1;\
if (typeid(n) == typeid(int)) {\
for(int i = 0; i < n; i++)\
product *= x;}\
else product = my_pow(x,n);\
product;\
})
Result: runtime = 51.86 sec
Third option: suggestion given in answer with template<typename type_t>
template<typename type_t>
inline double pow(const double x, type_t n)
{
// This is compile time checking of types.
// Don't use the RTTI thing you are trying to do
//if constexpr (is_floating_point_v<type_t>)
if (typeid(n) != typeid(int))
{
return pow(x, n);
}
else
{
double value = 1;
for (type_t i = 0; i < n; ++i) value *= x;
return value;
}
}
Result: runtime = 52.84 sec
So finally, from these first tests, the best option would be the second one where I use a macro combined with a function that calls the general case of the pow function (both integer and floating exponent).
Is there a more efficient solution or is the second option the best?
| If you only need to switch between floating point types or not you can use templates instead of macros.
#include <cassert>
#include <cmath>
#include <type_traits>
namespace my_math
{
template<typename type_t>
inline double pow(const double x, type_t n)
{
// this is compile time checking of types
// don't use the rtti thing you are trying to do
if constexpr (std::is_floating_point_v<type_t>)
{
return std::pow(x, n);
}
else
{
double value = 1;
for (type_t i = 0; i < n; ++i) value *= x;
return value;
}
};
}
int main()
{
assert(my_math::pow(2, 0) == 1);
assert(my_math::pow(2.0, 1) == 2.0);
assert(my_math::pow(3.0, 2.0) == 9.0);
assert(my_math::pow(4.0f, 3.0f) == 64.0f);
return 0;
}
|
69,661,240 | 69,661,551 | Can Someone help me point out where my code is going wrong with the output? | #include <iostream>
#include <vector>
using namespace std;
/*
Sample Input:
2 2 ---------> Number of Arrays, Number of commands
3 1 5 4 -----> length of array, elements to add
5 1 2 8 9 3 -> length of array, elements to add
0 1 ---------> Command 1, row and column (first element of main vector, second element)
1 3 ---------> Command 2, row and column (second element of main vector, fourth element)
*/
int main()
{ //taking input of n and q.
int n, q;
cin >> n >> q;
//make a main array to maintain sub arrays within and use queries on it.
vector < vector<int> > main_vector;
//make a sub vector and input it's value's using for loop
vector <int> sub_vector;
//declaring a variable to take input and keep pushing into sub_vector
int input_element;
//take input length of each vector in for loop
int length_of_sub_vector;
// now take n vectors input :
for(int x = 0; x < n; x++)
{
//taking input length
cin >> length_of_sub_vector;
for(;length_of_sub_vector > 0; length_of_sub_vector--)
{
cin >> input_element;
sub_vector.push_back(input_element);
}
main_vector.push_back(sub_vector);
}
//variable t and y for row and column
int t, y;
vector <int> to_print;
for(int p = 0; p < q; p++) //take input of the q following queries
{
cin >> t >> y;
to_print.push_back(main_vector[t][y]);
}
for(int u = 0; u < to_print.size(); u++)
{
cout << to_print[u] << endl;
}
}
The original Problem is over here : https://www.hackerrank.com/challenges/variable-sized-arrays/problem
I know there must be a better way to solve this question but I would like to learn what part of my code is leading to the undesired output, Thanks in Advance.
Output Should be :
5
9
Output I'm getting :
5
1
Live demo
| You are missing a vector.clear() statement in your for loop that inserts values into the sub_vectors.
// now take n vectors input :
for(int x = 0; x < n; x++)
{
//taking input length
cin >> length_of_sub_vector;
for(;length_of_sub_vector > 0; length_of_sub_vector--)
{
cin >> input_element;
sub_vector.push_back(input_element);
}
main_vector.push_back(sub_vector);
sub_vector.clear();
}
|
69,662,180 | 69,663,769 | fgets not able to read from pipe twice on Ubuntu 20.04 | I have the following code that used to work on Ubuntu 18.04. Now, I compiled and run it in Ubuntu 20.04, and, for some reason, the code stop working.
The code is meant to read from a named pipe. To test it, I create the pipe with mkfifo /tmp/pipe and then I write into the pipe with echo "message" >> /tmp/pipe.
The first time the fgets() method is executed, the function returns the expected value from the pipe; but from the second invocation on, the method returns NULL and the code gets stuck on the loop even when I execute several echo commands.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <sstream>
#include <fstream>
#include <limits>
#include <iomanip>
#include <iostream>
#include <cstdlib>
using namespace std;
FILE* result_pipe_stream;
string read_result_from_pipe(){
if (result_pipe_stream == NULL){
printf("\n[BINDING-COMMONS] ERROR: Pipe is not set");
return NULL;
}
std::stringstream oss;
while (1) {
char buf[BUFSIZ];
if( fgets (buf, BUFSIZ, result_pipe_stream) != NULL ) {
int buflen = strlen(buf);
if (buflen >0){
if (buf[buflen-1] == '\n'){
buf[buflen-1] = '\0';
oss << buf;
return oss.str();
} else {
oss << buf;
// line was truncated. Read another block to complete line.
}
}
}
}
}
int main(int argc, char *argv[]){
result_pipe_stream = fopen("/tmp/pipe" , "r");
while (1){
cout << read_result_from_pipe() << '\n';
}
}
Why is the code not working anymore? I assume that some library has changed in the distribution and fgets is no longer able to read properly from the pipe
How can I workaround that problem?
| if( fgets (buf, BUFSIZ, result_pipe_stream) != NULL ) --> Once fgets() returns NULL due to end-of-file, it will continue to return NULL on subsequent calls without reading unless the end-of-file indicator for result_pipe_stream is cleared - like with clearerr(). Codes gets stuck in an infinite loop, never reading anymore and it should.
The real question is why it "worked" in Ubuntu 18.04. I suspect that version was not compliant.
while (1) {
char buf[BUFSIZ];
if( fgets (buf, BUFSIZ, result_pipe_stream) != NULL ) {
...
}
// Perhaps assess why here, end-of-file, input error, too often here, ...
clearerr(result_pipe_stream); // add
}
|
69,662,346 | 69,757,714 | CMake, JNI boost read json file - Android | What is the proper way to open a file with boost::property_tree::json_parser::read_json
Current tree:
boost::property_tree::ptree config;
boost::property_tree::json_parser::read_json("conf/file.json", config);
But I get the error that it cannot find the file
terminating with uncaught exception of type boost::wrapexceptboost::property_tree::json_parser::json_parser_error: conf/file.json: cannot open file
How would I go on about copying the file into the device and being able to open it?
| I used this code to get it working, basically you copy the file from Android raw dir to some location on the device that the C++ JNI code can see.
MainActivity code:
private static final String RES_RAW_CONFIG_PATH_ENV_VAR = "RES_RAW_CONFIG_PATH";
private static final String RES_RAW_CONFIG_FILE_NAME = "res_raw_config.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
initResRawConfig(true); // this will copy the file
...
}
private boolean existsInFilesDir(String fileName) {
val file = File(filesDir, fileName)
return file.exists()
}
private void initResRawConfig(boolean forceCopy) {
if (existsInFilesDir(RES_RAW_CONFIG_FILE_NAME) && !forceCopy) {
Log.d(TAG, "Config file: " + RES_RAW_CONFIG_FILE_NAME + " already exists in " + getFilesDir().toString());
}
else {
copyFileFromResToFilesDir(R.raw.res_raw_config, RES_RAW_CONFIG_FILE_NAME);
Log.d(TAG, "Config file: " + RES_RAW_CONFIG_FILE_NAME + " copied to " + getFilesDir().toString());
}
// Set Environment Variable to get path from native
try {
Os.setenv(RES_RAW_CONFIG_PATH_ENV_VAR, getFilesDir().getAbsolutePath(), true);
} catch (ErrnoException e) {
e.printStackTrace();
}
}
private void copyFileFromResToFilesDir(int fromResId, String toFile) {
InputStream is = getResources().openRawResource(fromResId);
byte[] buffer = new byte[4096];
try
{
FileOutputStream fos = openFileOutput(toFile, Context.MODE_PRIVATE);
int bytes_read;
while ((bytes_read = is.read(buffer)) != -1)
fos.write(buffer, 0, bytes_read);
fos.close();
is.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public String getResRawConfigDir()
{
return getFilesDir().toString();
}
JNI code:
// get file path from java method
std::string getResRawConfigDirFromJava(JNIEnv *env, jobject obj) {
jclass clazz = env->GetObjectClass(obj); // or env->FindClass("com/example/myapp/MainActivity");
jmethodID method = env->GetMethodID(clazz, "getResRawConfigDir", "()Ljava/lang/String;");
jobject ret = env->CallObjectMethod(obj, method);
auto jConfigDirPath = (jstring) ret;
return std::string(env->GetStringUTFChars(jConfigDirPath, nullptr));
}
extern "C" JNIEXPORT jstring
sampleFunc(JNIEnv *env, jobject thiz) {
std::string configPath = getResRawConfigDirFromJava(env, thiz);
std::string filePath = configPath + "/" + "res_raw_config.json";
}
Ref: https://github.com/nkh-lab/ndk-config-provider/blob/master/app/src/main/java/com/example/myapp/MainActivity.java
|
69,662,387 | 69,662,475 | How can I fix the missing template arguments before '(' token problem here? | I am getting the problem on line 15 and 20 where i am trying to pushback elements in to the pair vector
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
int main()
{
int x, y, a, b, c, d, j, m, v;
vector<pair<int, int> > ladder;
cin >> x >> y;
for (int i = 0; i < x; i++) {
cin >> a >> b;
ladder.push_back(pair(a, b));
}
vector<pair<int, int> > snake;
for (int i = 0; i < y; i++) {
cin >> c >> d;
snake.push_back(pair(c, d));
}
vector<int> moves;
cin >> v;
while (v != 0) {
moves.push_back(v);
v = 0;
cin >> v;
}
return 0;
}
My errors are:
prog.cpp: In function ‘int main()’:
prog.cpp:15:30: error: missing template arguments before ‘(’ token
ladder.push_back(pair(a, b));
^
prog.cpp:20:29: error: missing template arguments before ‘(’ token
snake.push_back(pair(c, d));
I have the code here to test:
https://ideone.com/ZPKP4s
| Your issue is on these two lines:
ladder.push_back(pair(a, b));
ladder.push_back(pair(c, d));
You need to specify what types of pairs these are:
ladder.push_back(pair<int, int>(a, b));
ladder.push_back(pair<int, int>(c, d));
|
69,662,832 | 69,663,400 | How to add void/null as default argument to a function/lambda pointer, in C++? | Present signature is
template<class TypeData,typename TypeFunc>
bool isPrime(const TypeData& n,TypeFunc fSqrt,bool debug = false)
and this works perfectly with
std::cout<<(isPrime(n,fSqrt)?"Positive":"Negative")<<'\n';
But, my intension is something like
template<class TypeData,typename TypeFunc>
bool isPrime(const TypeData& n,TypeFunc fSqrt = nullptr,bool debug = false)
or
template<class TypeData,typename TypeFunc>
bool isPrime(const TypeData& n,TypeFunc fSqrt = NULL,bool debug = false)
to be called by
std::cout<<(isPrime(n)?"Positive":"Negative")<<'\n';
Overloading is not possible due to a static variable inside the function.
Only different class TypeData should give different template-functions for this function-template.
Please help me out with the proper syntax. If C++ does not support this, what is an alternative approach I can use?
Compile Errors
for TypeFunc fSqrt = nullptr
main.cpp:90:23: error: no matching function for call to ‘isPrime(int&)’
std::cout<<(isPrime(n)?"Positive":"Negative")<<'\n';
^
main.cpp:9:49: note: candidate: template bool isPrime(const TypeDate&, TypeFunc, bool)
template<class TypeDate,typename TypeFunc> bool isPrime(const TypeDate& n,TypeFunc fSqrt = nullptr,bool debug = false) {
^~~~~~~
main.cpp:9:49: note: template argument deduction/substitution failed:
main.cpp:90:23: note: couldn't deduce template parameter ‘TypeFunc’
std::cout<<(isPrime(n)?"Positive":"Negative")<<'\n';
^
for TypeFunc fSqrt = NULL
main.cpp:90:23: error: no matching function for call to ‘isPrime(int&)’
std::cout<<(isPrime(n)?"Positive":"Negative")<<'\n';
^
main.cpp:9:49: note: candidate: template bool isPrime(const TypeDate&, TypeFunc, bool)
template<class TypeDate,typename TypeFunc> bool isPrime(const TypeDate& n,TypeFunc fSqrt = NULL,bool debug = false) {
^~~~~~~
main.cpp:9:49: note: template argument deduction/substitution failed:
main.cpp:90:23: note: couldn't deduce template parameter ‘TypeFunc’
std::cout<<(isPrime(n)?"Positive":"Negative")<<'\n';
^
They are basically the same.
| Overloading actually is an option, you can let one overload call the other one:
template<class TypeData, typename TypeFunc>
bool isPrime(const TypeData& n, TypeFunc fSqrt, bool debug = false);
template<class TypeData>
bool isPrime(const TypeData& n, bool debug = false)
{
using std::sqrt;
if constexpr (std::is_integral_v<TypeData>)
{
return isPrime(n, static_cast<double(*)(double)>(sqrt), debug);
}
else if constexpr (std::is_floating_point_v<TypeData>)
{
return isPrime(n, static_cast<TypeData(*)(TypeData)>(sqrt), debug);
}
else
{
// this covers e.g. std::complex
return isPrime(n, static_cast<TypeData(*)(TypeData const&)>(sqrt), debug);
// for any other type we assume the overload accepts by
// const reference as well (if there's one at all...)
// if not, we still can fall back to the other overload
}
}
This solution selects an appropriate square root function right away, something you would have had to solve anyway if the function argument had defaulted to nullptr.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.