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 |
|---|---|---|---|---|
70,944,767 | 70,947,619 | warning: control reaches end of non-void function [-Wreturn-type] removed when declaring method inline | With this code
enum EnumTypes
{
one,
two
};
int enum_to_int(EnumTypes enum_type)
{
switch(enum_type)
{
case one: return 1;
case two: return 2;
}
}
I get the following warning:
: In function 'int enum_to_int(EnumTypes)':
:14:1: warning: control reaches end of non-void function [-Wreturn-type]
14 | }
, which I understand is a valid warning since enum_type could have some other value stored than one and two.
However, if I mark the method as inline as the following, the warning disappears.
enum EnumTypes
{
one,
two
};
inline int enum_to_int(EnumTypes enum_type)
{
switch(enum_type)
{
case one: return 1;
case two: return 2;
}
}
Should there not be a warning if function is marked inline?
Link without inline: https://godbolt.org/z/jcscchEGh
Link with inline: https://godbolt.org/z/6qfeWeYsd
| In contrast to a non-inline function with external linkage, an inline function or a function with internal linkage (static) is guaranteed to be defined in every translation unit (odr-)using the function (or else the program is ill-formed).
The compiler is therefore just being "lazy" and doesn't emit a definition for the inline function, since you don't (odr-)use it in the translation unit.
If you (odr-)use it in any way, it will be emitted and the checks wont be skipped. It is enough to take a pointer to the function:
auto ptr = &enum_to_int;
And then the warning will appear again.
It is probably reasonable that the compiler doesn't check the function for such issues in a translation unit where the definition doesn't need to be emitted. It is guaranteed that the program either doesn't use the function at all, in which case the problem doesn't really matter, or it is (odr-)used in another translation unit and the warning will be produced there.
Checking it in all translation units would probably just be wasted time.
|
70,944,859 | 70,946,713 | Memory leaks using JNI: are we releasing objects property? | IMPORTANT NOTE: This snippet of code is not a native function called from Java. Our process is written in C++, we instantiate a Java VM, and we call Java functions from C++, but never the other way around: Java methods never calls native functions, but native functions instantiate Java objects and call Java functions on them.
We are doing something like this:
void some_fun()
{
// env is a JNIEnv*, cls (and cls2) a jclass, and init (and mid) a jmethodID
jobject obj = env->NewObject(cls, init);
fill_obj(obj, cpp_data);
env->callStaticVoidMethod(cls2, mid, obj);
// env->DeleteLocalRef(obj); // Added out of desperation.
}
Where fill_obj depends on the kind of cpp_data that must be set as fields of obj. For example, if the Java class cls contains an ArrayList, cpp_data will contain, for example, a std::vector. So the fill_obj overload will look like this:
void fill_obj(jobject obj, SomeType const& cpp_data)
{
std::vector<SomeSubType> const& v = cpp_data.inner_data;
jobject list_obj = env->NewObject(array_list_class_global_ref, its_init_method);
for (auto it = v.begin(); it != v.end(); ++it) {
jobject child_obj = env->NewObject(SomeSubType_class_global_ref, its_init_method);
fill_obj(child_obj , *it);
env->CallBooleanMethod(list_obj, add_method, child_obj);
}
env->SetObjectField(obj, field_id, list_obj);
}
According to our understanding on the JNI docs, that code should not have any memory leaks since local objects are destroyed when the native method ends. So, when the first fill_obj ends, at C++ side there's no more references to list_obj or any of its childs, and when some_fun ends, any reference of obj at C++ side is gone as well.
My understanding is that jobject contains some sort of reference counter and when that reference counter reachs 0, then there's no more references to the Java object at C++ side. If there's no more references to the object at Java side either, then the Java's garbage collector is free to release the resources occupied by the object.
We have a method that, when called, creates thousand of those objects, and each time that method is called, the memory that the process occupies in RAM (the resident memory) grows by more than 200 MiB, and that memory is never released.
We have added an explicit call to DeleteLocalRef but the result is the same.
What is going on? Are we doing something wrong?
| Note the section Implementing Local References from the JNI specification:
To implement local references, the Java VM creates a registry for each transition of control from Java to a native method. A registry maps nonmovable local references to Java objects, and keeps the objects from being garbage collected. All Java objects passed to the native method (including those that are returned as the results of JNI function calls) are automatically added to the registry. The registry is deleted after the native method returns, allowing all of its entries to be garbage collected.
The term “after the native method returns” means the reversal of the “transition of control from Java to a native method”, in other words, the method declared inside a Java class using the keyword native has been called and returns to the caller.
Once this is understood, it’s also clear how to read the Global and Local References section
Local references are valid for the duration of a native method call, and are automatically freed after the native method returns.
So when you have code that runs for a long time before returning to the Java caller or has no Java caller at all, there is no way around deleting references manually using DeleteLocalRef.
As Remy Lebeau mentioned, you can also use PushLocalFrame and PopLocalFrame to perform bulk destruction of references created between two points.
Mind that the destruction of the reference does not imply the destruction of the referenced object, but just not to prevent the garbage collection of the object. So after calling env -> CallBooleanMethod(list_obj, add_method, child_obj);, you can destroy the child_obj reference, because the object is still referenced by the list you’re referencing via list_obj, so the added object will be kept as long as it is still in use.
|
70,944,880 | 70,945,389 | Correctly move from a data member of a temporary object | Consider the following C++-Code
#include <iostream>
using namespace std;
struct WrapMe
{
WrapMe() { cout << "WrapMe Default Ctor of: " << this << endl; }
WrapMe(const WrapMe& other) { cout << "WrapMe Copy Ctor of " << this << " from " << &other << endl; }
WrapMe(WrapMe&& other) noexcept { cout << "WrapMe Move Ctor of " << this << " from " << &other << endl; }
~WrapMe() { cout << "Wrap Me Dtor of" << this << endl; }
};
struct Wrapper1
{
WrapMe& data()& { return member; }
WrapMe data()&& { return std::move(member); }
WrapMe member;
};
struct Wrapper2
{
WrapMe& data()& { return member; }
WrapMe&& data()&& { return std::move(member); }
WrapMe member;
};
int main()
{
auto wrapMe1 = Wrapper1().data();
auto wrapMe2 = Wrapper2().data();
}
with the output
WrapMe Default Ctor of: 00000092E7F2F8C4
WrapMe Move Ctor of 00000092E7F2F7C4 from 00000092E7F2F8C4
Wrap Me Dtor of00000092E7F2F8C4
WrapMe Default Ctor of: 00000092E7F2F8E4
WrapMe Move Ctor of 00000092E7F2F7E4 from 00000092E7F2F8E4
Wrap Me Dtor of00000092E7F2F8E4
[...]
Which is the correct way to move from the WrapMe member: Like Wrapper1 (return by value) or like Wrapper2 (return by rvalue-reference) does? Or are both ways equivalent here, as the ouput suggests? If not, why?
| WrapMe&& data()&& { return std::move(member); }
This doesn't actually move anything. It just returns a rvalue reference to the member. For example I could do
auto&& wrapMe2 = Wrapper2().data();
and now wrapMe2 will be a dangling reference or
auto w = wrapper2();
auto&& wrapMe2 = std::move(x).data();
Now I have a reference to the member of w without w having changed at all.
Only because the move constructor of WrapMe is called to initialize the wrapMe2 object in the original line, a move operations actually takes place.
The version
WrapMe data()&& { return std::move(member); }
calls the move constructor already to construct the return value. The returned value will never refer to the original object or its member.
The line
auto wrapMe1 = Wrapper1().data();
then calls the move constructor again to initialize wrapMe1 from the return value of .data(). The compiler is however allowed to elide this second move constructor call and instead construct wrapMe1 directly from the expression in the return statement. This is why you see the same result.
With C++17 or later this elision would even be mandatory.
I don't know your use case, so I cannot be sure what the correct approach is, but just guessing on what you want to do:
For consistency between the two overloads, I would use the reference-returning version. Having data provide modifiable access to the member for lvalues, but not for rvalues, would be confusing.
However, you don't really need a member function to do this. Through data the caller has full control over the member anyway, so you could just make the member public from the start and then it could be used in the same way directly.
|
70,945,481 | 70,945,678 | directory_iterator skip over inaccessible files folders Windows | I am trying to iterate over all the folders in my C:\ directory, and ONLY in the C:\ directory. Not in any subfolders. My current problem is that it includes inaccessible files and folders like swapfile.sys or System Volume Information when iterating. How can I check the flags or whatnot to exclude such objects?
for (const auto& entry : std::filesystem::directory_iterator(dir))
{
// Have the if() check here to see if it's accessible
directory.emplace_back(f);
}
| You can use fs::status(entry).permissions() to get the permissions of the current entry and choose whether to skip it according to its flag value.
for (const auto& entry : fs::directory_iterator(dir)) {
auto p = fs::status(entry).permissions();
if ((p & fs::perms::owner_read) != fs::perms::none)
directory.emplace_back(f);
}
|
70,946,223 | 70,946,553 | Why is constexpr of std::wstring().capacity() not equal to std::wstring().capacity()? | I'm not sure if I'm too naïve or simply too unknowing.
But why does the following differ?
constexpr auto nInitialCapacity1 = std::wstring().capacity();
const auto nInitialCapacity2 = std::wstring().capacity();
In Visual Studio 2022/17.0.5 the code above results in:
nInitialCapacity1 = 8
nInitialCapacity2 = 7
Why is the result of the constexpr (compile time) version not equal to the const version of the call?
Thanks for any explanation!
| Microsoft's STL disables short string optimisation in constant evaluated contexts, so it allocates memory instead.
The allocations are always one more than a power of two, so the capacity (which excludes the last L'\0') is always a power of two.
In the non-constant-evaluated version, the short string buffer can hold 8 characters, one of which is a L'\0', so the capacity is 7.
|
70,946,268 | 70,947,984 | Is it possible to find the seed for GoogleTest to run a specific order if the order is known? | I have been given a list of 25 tests and a order to run them in that is supposedly causing a failure in the last test. Unfortunately the tool that was used to find this failure does not save the seed that was used by GoogleTests shuffle to trigger this order.
So I can of course just run the tests with shuffle and repeat a huge number of times until this order is triggered, but there is quite a lot of permutations to work through. As far as I can tell there isn't a way to just say "Hey run these tests in this order" with GoogleTest aside from knowing the seed to trigger the order.
I'm hoping there might be a way to find that seed without actually running the tests - ideally something that could be given the desired order and output the seed, but really just something that given the gtest_filter value just dumps out massive amounts of potential test orders and the seeds that trigger them would be fine.
Is there any options out there, or I'm I just running with shuffle until I get it?
| There is no such option to specify the order of the tests.
However, By default (i.e. if --gtest_shuffle is not enabled), they run in the declaration order.
I can think of three ways of achieving what you want:
Use your favorite scripting language (e.g. bash, python, nodejs, etc) and regular expressions to modify the original order of the tests to your desired order and create a new test file which then you run without --gtest_shuffle.
Hack into Google test's source code. You can modify the shuffle function to shuffle the code in the order that you want.
Look into Registering tests programmatically. I think you might be able to register your tests one by one in the order that you want, and I think Googletest will observe that order. But this also requires processing your original test file.
Obviously, none of these methods are ideal, but they might work for a one-off experiment to find the order that you want.
|
70,946,571 | 70,947,634 | How can I parse a char pointer string and put specific parts it in a map in C++? | Lets say I have a char pointer like this:
const char* myS = "John 25 Lost Angeles";
I want to parse this string and put it in a hashmap, so I can retrieve the person's age and city based on his name only. Example:
std::map<string, string> myMap;
john_info = myMap.find("John");
How can I do this to return all of John's info in an elegant way ? I come from a Java background and I really want to know how this is properly done in C++. That would also be cool if you can show me how to do this using a boost map (if it is easier that way). Thank you.
| I'm going to show you one way to do it using Boost:
Live On Coliru
#include <map>
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>
#include <iostream>
namespace x3 = boost::spirit::x3;
using Name = std::string;
struct Details {
unsigned age;
std::string city;
};
using Map = std::map<Name, Details>;
using Entry = Map::value_type;
BOOST_FUSION_ADAPT_STRUCT(Details, age, city)
int main() {
Map persons;
std::string_view myS = //
"John 25 Lost Angeles\n"
"Agnes 22 Minion Appolis";
auto name = x3::lexeme[+x3::graph];
auto age = x3::uint_;
auto city = x3::raw[*(x3::char_ - x3::eol)];
auto details = x3::rule<struct details_, Details>{} = age >> city;
auto line = name >> details;
auto grammar = x3::skip(x3::blank)[line % x3::eol];
if (x3::parse(myS.begin(), myS.end(), grammar, persons)) {
for (auto& [name, details] : persons)
std::cout << name << " has age " << details.age << "\n";
for (auto& [name, details] : persons)
std::cout << name << " lives in " << details.city << "\n";
}
// lookup:
std::cout << "John was " << persons.at("John").age << " years old at the time of writing\n";
}
Prints
Agnes has age 22
John has age 25
Agnes lives in Minion Appolis
John lives in Lost Angeles
John was 25 years old at the time of writing
To use a hash-map, just replace
using Map = std::map<Name, Details>;
with
using Map = std::unordered_map<Name, Details>;
Now the output will be in implementation-defined order.
CAVEAT
If this is home-work, please don't use this (kind of) approach. It will be very clear it was copy-pasted. Never use code you don't fully understand.
|
70,946,996 | 70,978,374 | VSCode marks GPIO_TypeDef in HAL library as unknown | I have some functions that refer to GPIO_TypeDef struct from STM32_HAL library and in Keil I recieve no errors in compilation, but VSCode marks it as "unknown identificator" error. I fixed it with adding
#include "stm32f103xe.h"
to main.hand both Keil and VScode now take it with no problems, but maybe I had to change something in VSCode settings to fix that problem.
| I found answer in CubeIDE directives. Add theese to C_Cpp.default.defines
(You can simply do this through Settings->Extensions->C/C++->Defines)
__CC_ARM
STM32F1xx
USE_HAL_DRIVER
DEBUG
|
70,947,360 | 70,947,860 | String Literal in the temporary object? | I am beginner in C++ and its low-level layer (in comparison with Python and so on). I have read on StackOverflow that string literals go into the Read-Only data section (String literals: Where do they go?), but currently I am reading a C++ book (by Bjarne Stroustrup) and it is written in there that temporary objects end their life at the end of an expression, so:
string var1 = "Hello ";
string var2 = "World";
string var3 = var1 + var2; // string temp = "Hello World" and assign it to var3
After execution, will we have two "Hello World" or only one copy will be left?
Hardware:
OS: Windows 11;
Compiler: MSVC;
Standard: C++11
I understand that possibly it can be implementation-defined, but if it is so, please specify for the x86 platform.
| String literals are the objects that are referred to specifically with the syntax
"Hello "
or
"World"
That is what literal means, an atomic syntax for a value. It does not refer to string values in general.
String literals are not temporary objects. They are objects stored in an unspecified way (in practice, often in read-only memory, as you indicated) and have static storage duration, meaning they exist for the duration of the complete program execution.
When you write
string var1 = "Hello ";
you are creating a std::string object, and this object is initialized from the string literal. It is neither itself a string literal, nor does it hold or refer to one. It will simply copy the characters from the literal into some storage it manages itself. The var1 object (if declared at block scope, ie inside a function) has automatic storage duration, meaning that it lives until the end of the scope in which it was declared.
The line
string var3 = var1 + var2;
used to (prior to C++17) create a temporary std::string object, which was returned by the + operator overload of std::string. Then var3 was move-constructed from this temporary. The temporary resulting from var1 + var2 would then live until the end of the full expression, meaning until after the initialization of var3 was finished.
However, since C++17, there is no temporary involved here anymore. Instead, the + operator overload will directly construct the var3 object. Before C++17, this was also allowed to happen as so-called return value optimization.
So, in your code, there doesn't exist any "Hello World" string literal, but there exists exactly one string object that holds the characters Hello World, and if you are using a pre-C++17 version, there may be additionally one temporary std::string object that held the same value, but was destroyed after the initialization of var3.
|
70,948,513 | 70,949,326 | Dependent sibling subdirectories in CMake | My current project has the following structure:
root
|- parser
| |- include // a directory for headers
| |- src // a directory for sources
| |- parser.yy
| |- scanner.ll
| |- CmakeLists.txt
|
|- preprocessor
| |- include // a directory for headers
| |- src // a directory for sources
| |- CmakeLists.txt
|
|- main.cpp
|- CMakeLists.txt
Now I want to start generating assembly codes. I have to use staticstack and codegen (are classes which are going to be defined) in the parser.yy and in srcfolder of the parser foler.
I cannot figure out how to do that.
What's the best practice in CMake to do this ?
Should I make subdirectories named semstack and codegen in parser folder ? This doesn't seem correct to me since as a CMake project gets larger the hierarchy will get deeper and if more dependencies are there then it would be a mess.
Should I make these subdirectories in the root ? If then what is the syntax in CMake to use sibling subdirectory ?
|
If then what is the syntax in CMake to use sibling subdirectory ?
There is no special syntax for this since normal (i.e. not IMPORTED) targets are global. If you define a library in one subdirectory, it may be used in any other via target_link_libraries.
For instance:
# parser/CMakeLists.txt
add_library(parser ...)
add_library(proj::parser ALIAS parser)
target_include_directories(
parser PRIVATE "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>")
target_link_libraries(
parser PRIVATE proj::semstack proj::codegen)
The code for other subdirectories is similar.
# ./CMakeLists.txt
cmake_minimum_required(VERSION 3.22)
project(proj)
add_subdirectory(semstack)
add_subdirectory(codegen)
add_subdirectory(parser)
add_subdirectory(preprocessor)
add_executable(main main.cpp)
target_link_libraries(
main PRIVATE proj::parser proj::preprocessor)
I create and link to ALIAS targets to avoid a typo in a target name being forwarded to the linker verbatim (names with :: in CMake are always considered targets and this is validated at generation time).
|
70,948,614 | 70,948,859 | Problem with overloading a function for literal strings | I have a template function that handles rvalues arguments. The argument is supposed to expose a certian function. For those rvalues that do not have this function, I need to use template specialization to handle the exceptions. The problem I have is with string literals. Here's a short example of what I am trying to do.
#include <iostream>
#include <string>
using namespace std;
struct A
{
template < class T > void foo (T && x)
{
x.baa();
}
};
struct B{
void baa(){
cout << "I have baa()" << endl;
};
};
template <> void
A::foo (std::string && x)
{
cout << "I am a std::string, I don't have baa()" << endl;
};
template <> void
A::foo (char *&&x)
{
cout << "I am a char* and I am sad because nobody ever calls me" << endl;
};
int
main ()
{
A a;
a.foo (B());
a.foo (std::string ("test1"));
a.foo ("test2"); // this line causes a compiler error
return 0;
}
If I try to compile the snippet above, I get the following error
main.cpp:16:7: error: request for member ‘baa’ in ‘x’, which is of non-class type ‘const char [6]’
16 | x.baa();
Obviously the compiler is trying to apply the generic function rather than the specialization for char*. How can I write a specialization that captures literal strings of any length?
| Note that "test2" literal is an lvalue, while char *&&x is an rvalue reference and cannot be bound to an lvalue.
|
70,948,707 | 70,948,730 | C++: Is a + b + c always equal to c + b + a? Assuming a,b,c are double | I have two vectors of double. The value of the double is between -1000 and 1000.
Both vectors contain the same numbers, but the order is different.
For example
Vector1 = {0.1, 0.2, 0.3, 0.4};
Vector2 = {0.4, 0.2, 0.1, 0.3};
Is there a guarantee that the sum of Vector1 will be exactly equal to the sum of Vector2, assuming the sum is done via:
double Sum = 0;
for (double Val : Vector) Sum += Val;
I am worried about double imprecisions.
|
Is there a guarantee that the sum of Vector1 will be exactly equal to the sum of Vector2, assuming the sum is done via:
No, there is no such guarantee in the C++ language.
In fact, there is an indirect practical guarantee - assuming typical floating point implementation - that the results would be unequal. (But compilers have ways of disabling such guarantees, and of enabling unsafe floating point optimisations that may cause the sum to be equal).
The difference is likely to be very small with the given input, but it can be very large with other inputs.
|
70,949,064 | 70,953,031 | Count elements in texture | I have a 3D texture of 32-bit unsigned integers initialized with zeroes. It is defined as follows:
D3D11_TEXTURE3D_DESC description{};
description.Format = DXGI_FORMAT_R32_UINT;
description.Usage = D3D11_USAGE_DEFAULT;
description.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
description.CpuAccessFlags = 0;
description.MipLevels = 1;
description.Width = ...;
description.Height = ...;
description.Depth = ...;
I am writing to this texture in a compute shader to set a bit on specified position if a certain condition is fulfilled:
RWTexture3D<uint> txOutput : register(u0)
cbuffer InputBuffer : register(b0)
{
uint position;
/** other elements **/
}
#define SET_BIT(value, position) value |= (1U << position)
[numthreads(8, 8, 8)]
void main(uint3 threadID : SV_DispatchThreadID)
{
if(/** some condition **/)
{
uint value = txOutput[threadID];
SET_BIT(value, position);
txOutput[threadID] = value;
}
}
I need to know how many elements of this texture is filled at a certain bit position in a code behind in C++. How could this be done?
| You will have to read back the texture to the cpu with the ID3D11DeviceContext::Map API
https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-map
You will get out a void* you will cast to uint32_t* which will point to the start of your data.
You need to get better a looking up the DirectX documentation, its really quite good documentation. There are a lot harder things you will need to find in the documentation if you keep doing 3D graphics.
|
70,949,264 | 70,954,480 | If statement in a template only run the first if-statement - QT | template <class T> void IOcalibrationWindow::setChildIntoIOcalibrationObject(int i, QString firstChildName, QString lastChildName, QString firstIocalibrationMethodName, QString lastIOcalibrationMethodName){
/* Get the index as string */
QString index = QString::number(i);
/* Create the UI field name */
QString childName = firstChildName + index + lastChildName;
/* Create the object name */
const char *IOcalibrationMethodName = (firstIocalibrationMethodName + index + lastIOcalibrationMethodName).toLatin1().data();
/* Get UI child */
T *uIchild = findChild<T*>(childName);
/* Get calibration object */
const QMetaObject *IOcalibrationMetaObject = iOcalibration.metaObject();
/* Insert into object */
if(std::strcmp(T::staticMetaObject.className(), "QDoubleSpinBox") != 0)
IOcalibrationMetaObject->invokeMethod(&iOcalibration, IOcalibrationMethodName, Qt::DirectConnection, Q_ARG(double, uIchild->value()));
else if(std::strcmp(T::staticMetaObject.className(), "QLineEdit") != 0)
IOcalibrationMetaObject->invokeMethod(&iOcalibration, IOcalibrationMethodName, Qt::DirectConnection, Q_ARG(QString, uIchild->text()));
}
This is an if-statement in QT where I'm accessing the specific method inside object iOcalibration. The method name is called IOcalibrationMethodName.
Sometimes the method IOcalibrationMethodName has an argument of double or QString.
It all depends on the template T, which can be QDoubleSpinBox or QLineEdit.
When I call the function, you can see that I'm using different templates.
setChildIntoIOcalibrationObject<QDoubleSpinBox>(i, "analogSingleInput", "MaxDoubleSpinBox", "setAnalogSingleInput", "Max");
setChildIntoIOcalibrationObject<QDoubleSpinBox>(i, "analogSingleInput", "MinDoubleSpinBox", "setAnalogSingleInput", "Min");
setChildIntoIOcalibrationObject<QLineEdit>(i, "analogSingleInput", "UnitLineEdit", "setAnalogSingleInput", "Unit");
Problem:
My problem with the code is that when I using the template class QLineEdit, I get an error at this code line.
IOcalibrationMetaObject->invokeMethod(&iOcalibration, IOcalibrationMethodName, Qt::DirectConnection, Q_ARG(double, uIchild->value()));
This should not be possible due to the if-statement.
The error is:
iocalibrationwindow.cpp:102:133: error: no member named 'value' in 'QLineEdit'
qobjectdefs.h:95:51: note: expanded from macro 'Q_ARG'
iocalibrationwindow.cpp:80:9: note: in instantiation of function template
specialization 'IOcalibrationWindow::setChildIntoIOcalibrationObject<QLineEdit>'
requested here
That means, that the first if-statement runs when I'm using template QLineEdit.
But the if-statement checks if the template is QDoubleSpinBox
if(std::strcmp(T::staticMetaObject.className(), "QDoubleSpinBox") != 0)
Question:
How can this be possible that QLineEdit till be equal as QDoubleSpinBox?
| I'm not entirely sure what you're trying to do but, from the code that's given, why can't you simply split out the uIchild->* calls into a couple of functions overloads? That would result in something like (untested)...
QGenericArgument fetch_data (QDoubleSpinBox *p)
{
return Q_ARG(double, p->value());
}
QGenericArgument fetch_data (QLineEdit *p)
{
return Q_ARG(QString, p->text());
}
template <class T> void IOcalibrationWindow::setChildIntoIOcalibrationObject(int i, QString firstChildName, QString lastChildName, QString firstIocalibrationMethodName, QString lastIOcalibrationMethodName){
/* Get the index as string */
QString index = QString::number(i);
/* Create the UI field name */
QString childName = firstChildName + index + lastChildName;
/* Create the object name */
const char *IOcalibrationMethodName = (firstIocalibrationMethodName + index + lastIOcalibrationMethodName).toLatin1().data();
/* Get UI child */
T *uIchild = findChild<T*>(childName);
/* Get calibration object */
const QMetaObject *IOcalibrationMetaObject = iOcalibration.metaObject();
/* Insert into object */
if(std::strcmp(T::staticMetaObject.className(), "QDoubleSpinBox") == 0)
IOcalibrationMetaObject->invokeMethod(&iOcalibration, IOcalibrationMethodName, Qt::DirectConnection, fetch_data(uIchild));
else if(std::strcmp(T::staticMetaObject.className(), "QLineEdit") == 0)
IOcalibrationMetaObject->invokeMethod(&iOcalibration, IOcalibrationMethodName, Qt::DirectConnection, fetch_data(uIchild));
}
[Note that I've changed the sense of the if (strcmp(... comparisons: strcmp returns zero if the strings are equal.]
|
70,949,454 | 70,949,496 | How do I open a file in main and then read from the file in another function? | In my main function I want to open a txt file while not hard-coding the file name, then call another function to read from the txt file.
I've tried to pass it as an argument according to another question thread, but it's solutions don't seem to work for me. The thread I looked at.
Sorry if this is an obvious question, I'm quite new to this so more in depth explanations are welcome.
Here's the code
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int readfile(double &a, double &b, double &c, ifstream filein)
{
filein >> a >> b >> c;
cout << a << b << c;
}
int main()
{
double a, b, c;
bool loop;
string infilename;
cout << "Enter the input filename to open\n";
cin >> infilename;
ifstream filein;
filein.open(infilename);
if (!filein)
{
cout << "Input file could not be opened";
return 1;
}
else
{
loop = true;
}
while (loop == true )
{
readfile(a, b, c, filein);
}
}
Here's the error message I'm getting
stackoverflow.cpp|42|error: use of deleted function 'std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const std::basic_ifstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]'|
| An std::ifstream object cannot be copied, so you cannot pass it by-copy to a function expecting it by-value.
But you can pass it by-reference without any problem:
int readfile(double &a, double &b, double &c, ifstream &filein)
As mentioned by @RemyLebeau in the comments, it is also preferable to take a std::istream& instead of a std::ifstream& as parameter, since all standard input streams including std::ifstream inherit from std::istream and so you could have a function that takes a reference to any input stream, not just a file input stream.
|
70,949,466 | 70,949,515 | How can I apply target-specific compiler and linker flags to subdirectories in CMake? | I am using CMake for a STM32 project as the project is outgrowing a plain Makefile. My directory structure looks something like what's below. I have an executable defined in the root CMakeLists.txt and somelib compiled as an OBJECT library which is added to the main CMakeLists.txt using add_subdirectory.
CMakeLists.txt
src/
├─ app/
│ ├─ main.c
├─ lib/
│ ├─ somelib/
│ │ ├─ CMakeLists.txt
│ │ ├─ somelib.h
│ │ ├─ somelib.c
I need to compile and link the source files with some flags specific to my microcontroller (i.e. -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard). I set up a toolchain file for the arm-none-eabi-gcc compiler and handled the compiler-specific flags there, but I'm hesitant to put the microcontroller-specific flags in that toolchain file as well since this project could expand to where I'd want to run my project on a different microcontroller.
My problem is if I were to define the microcontroller specific flags in the root CMakeLists.txt, when it comes time to compile somelib, I don't know how I can get somelib to compile with those flags. I know that I could use the global add_compile_options and add_libraries, but that seems like a bad idea, especially if I want to support a different microcontroller in the same project as well that would have a different set of flags. How can I propagate compiler and linker settings to the subdirectories for a specific executable?
|
I'm hesitant to put the microcontroller-specific flags in that toolchain file as well since this project could expand to where I'd want to run my project on a different microcontroller.
So don't be hesitant and do that. And when you will move to a different microcontroller, you will have a different toolchain file for it. Have one toolchain for every unique set of compiler flags. -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard flags definitely belong to a toolchain file.
When you want to support many many many toolchain files combinations and want to go a bit advanced, you might want to use the default behavior of sourcing Platform/${CMAKE_SYSTEM_NAME}-GNU-C-${CMAKE_SYSTEM_PROCESSOR}.cmake file from CMake module search path. That, combined with some custom variables -DUSE_FLOAT=hard/soft and -DMFPU=fpv4-sp-d16 makes a nice structure view.
|
70,949,593 | 70,958,888 | Using htons() in my code puts all zeros in the buffer and I don't understand why | I need to use htons() in my code to convert the little-endian ordered short to a network (big-endian) byte order. I have this code:
int PacketInHandshake::serialize(SOCKET connectSocket, BYTE* outBuffer, ULONG outBufferLength) {
memset(outBuffer, 0, outBufferLength);
const int sizeOfShort = sizeof(u_short);
u_short userNameLength = (u_short)strlen(userName);
u_short osVersionLength = (u_short)strlen(osVersion);
int dataLength = 1 + (sizeOfShort * 2) + userNameLength + osVersionLength;
outBuffer[0] = id;
outBuffer[1] = htons(userNameLength);// htons() here
printf("u_short byte 1: %c%c%c%c%c%c%c%c\n", BYTE_TO_BINARY(outBuffer[1]));
printf("u_short byte 2: %c%c%c%c%c%c%c%c\n", BYTE_TO_BINARY(outBuffer[2]));
for (int i = 0; i < userNameLength; i++) {
outBuffer[1 + sizeOfShort + i] = userName[i];
}
outBuffer[1 + sizeOfShort + userNameLength] = htons(osVersionLength);// and here
for (int i = 0; i < osVersionLength; i++) {
outBuffer[1 + (sizeOfShort * 2) + userNameLength + i] = osVersion[i];
}
int result;
result = send(connectSocket, (char*)outBuffer, dataLength, 0);
if (result == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
}
printf("PacketInHandshake sent: %ld bytes\n", result);
return result;
}
Which results in a packet like this to be sent:
As you see, the length indication bytes where htons() is used are all zeros, where they should be 00 07 and 00 16 respectively.
And this is the console output:
u_short byte 1: 00000000
u_short byte 2: 00000000
PacketInHandshake sent: 34 bytes
If I remove the htons() and just put the u_shorts in the buffer as they are, everything is as expected, little-endian ordered:
u_short byte 1: 00000111
u_short byte 2: 00000000
PacketInHandshake sent: 34 bytes
So what am I doing wrong?
| Converting endianess of a 16 bit number and storing it in a byte array is trivial, there is no need for library functions. Assuming 32 bit CPU:
uint16_t u16 = ...;
uint8_t out[2];
out[0] = ((uint32_t)u16 >> 8) & 0xFFu;
out[1] = ((uint32_t)u16 >> 0) & 0xFFu;
The casts and u suffix are there as a good habits to block implicit promotion to int which is problematic in some cases, since it's a signed number.
Since shifts don't care about the underlying endianess, the above code works for both big-to-little and little-to-big conversions, as long as you go from one to the other.
This scales to 32 bit types as:
uint32_t u32 = ...;
uint8_t out[4];
out [0] = ((uint32_t)u32 >> 24) & 0xFFu;
out [1] = ((uint32_t)u32 >> 16) & 0xFFu;
out [2] = ((uint32_t)u32 >> 8) & 0xFFu;
out [3] = ((uint32_t)u32 >> 0) & 0xFFu;
|
70,950,064 | 70,950,094 | While (true) forever loop expected body function error | I'm new here. I am trying to do a forever loop with while (true) but can't seem to get it working. I have tried iterations without int main(void) as well.
#include <cs50.h>
#include <stdio.h>
int main(void)
while (true)
{
printf("goddamnit\n")
}
~/ $ make goddamnit
[clang -ggdb3 -00 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno
-unused-parameter-Wno-unused-variable-Wshadow
goddamnit. c
-cryp
-Ics50 -1m -0 goddamnit
goddamnit.c:5:1: error: expected function body after function declarator
while (true)
A
1 error generated.
make:
*** \[‹builtin>; goddamnit\] Error 1][1]
Same problem on my <> loop
int i = 0;
while (i < 50)
{
printf(“goddamnit\n”);
i++;
}
Note: Image in linked error
| You are missing {} braces around your main() function's body, it needs to look more like this instead:
#include <cs50.h>
#include <stdio.h>
int main(void)
{ // <-- add this
while (true)
{
printf("goddamnit\n")
}
} // <-- add this
Block statements like if, for, while, etc can omit {} when their body is a single statement. Functions cannot do that.
|
70,950,122 | 70,950,188 | GetWindowTextA returns gibberish with unrelated code changes | I've tried this code which was supposed to get all window titles and positions and store them in vectors (here window titles are printed) but the outputs seemed completely random:
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <vector>
std::vector<LPSTR> buffs;
std::vector<int> rectposs;
BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam)
{
LPSTR buff;
if (IsWindowVisible(hWnd))
{
GetWindowTextA(hWnd, buff, 254);
buffs.push_back(buff);
RECT rect;
if (GetWindowRect(hWnd, &rect))
{
rectposs.push_back(rect.left);
rectposs.push_back(rect.right);
rectposs.push_back(rect.top);
rectposs.push_back(rect.bottom);
}
}
return TRUE;
}
int main()
{
EnumWindows(EnumWindowsProc, 0);
for (LPSTR buff : buffs)
{
std::cout << buff << std::endl;
}
return 0;
}
I expected the output to contain lines like Settings and Alarms and Clock since I had them open but instead everything was along the lines of ���$, and what confused me was if I removed lines 20-23 (push back the positions of windows) the problem was apparently fixed, which shouldn't be the case since it has nothing to do with GetWindowTextA or how I saved the window titles. As such I wasn't able to produce a minimum reproducible example since seemingly unrelated code seemed to change the output completely.
Are my suspicions that this has something to do with lines 20-23 overwriting the window titles correct? If so or otherwise how can I make sure it doesn't happen and still have the data I want?
| Your buff variable is an uninitialized pointer, it doesn't point anywhere meaningful. So your call to GetWindowTextA() is writing to random memory. To fix that, you need to allocate actual memory for it to write to.
After fixing that, you have another problem - you are pushing the same pointer into the buffs vector on each iteration. So, once the enumeration is finished, all entries will be pointing to the same memory, which will hold the result of the last call to GetWindowTextA(). To fix that, you need to make a copy of the buff data on each push. The easiest way to solve that is to change your buffs vector to hold std::string values instead of LPSTR pointers.
Lastly, I suggest changing the rectposs vector to hold actual RECT objects instead of the individual int values (though, you should consider defining a new struct/class to hold all of the window info you want, and then use a single vector to hold objects of that type).
Try this:
#include <iostream>
#include <vector>
#include <string>
#include <windows.h>
std::vector<std::string> buffs;
std::vector<RECT> rectposs;
BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam)
{
if (IsWindowVisible(hWnd))
{
CHAR buff[255]{};
GetWindowTextA(hWnd, buff, 254);
buffs.push_back(buff);
RECT rect;
GetWindowRect(hWnd, &rect);
rectposs.push_back(rect);
}
return TRUE;
}
int main()
{
EnumWindows(EnumWindowsProc, 0);
for (string& buff : buffs)
{
std::cout << buff << std::endl;
}
return 0;
}
|
70,950,130 | 70,962,891 | Suggestion for a pattern involving bits using bit manipulation | I currently have a structure like this
struct foo
{
UINT64 optionA = 0;
UINT64 optionB = 0;
UINT64 optionC = 0;
}
I am attempting to write a function for comparing two objects of foo based on optionA , optionB and optionC. Essentially what I would like the function to do is check if optionA is the same in both if no then return the lowest object back. If the optionA in both objects are the same then it will check optionB in both objects and would return the lowest one. If optionB are the same in both then it will look at optionC and return the lowest.
I am thinking that this could be accomplished by assigning a UINT64 no to each object.
Then assigning bits based on priority to that no and then comparing each and returning back the lesser one. I am not sure how to go about that approach any suggestions to do this would be appreciated.
| It would be simpler and more readable to just have a comparison function that directly compares the data members in the right order, but if having bit masks that store which data members are bigger is helpful for some other reason then here is how I would do it:
foo compare(foo x, foo y)
{
// needs to hold status for 3 data members (one bit each)
int x_status = 0, y_status = 0;
// each bit is 1 if this member is bigger, 0 if smaller
x_status |= (x.optionC > y.optionC)<<0;
x_status |= (x.optionB > y.optionB)<<1;
x_status |= (x.optionA > y.optionA)<<2;
// each bit is 1 if this member is bigger, 0 if smaller
y_status |= (x.optionC < y.optionC)<<0;
y_status |= (x.optionB < y.optionB)<<1;
y_status |= (x.optionA < y.optionA)<<2;
// so now we can compare the values
// if all the data members were bigger the value will be 7 (0b111)
// if all the data members were smaller the value will be 0 (0b000)
if (x_status < y_status) return x; else return y;
}
Try it online here: https://onlinegdb.com/XpdOSFLFa
|
70,950,267 | 70,950,291 | Why char is unsigned and int is signed by default? | I'm using gcc as my c++ compiler and when I declare a variable of int datatype then it is taken as signed by default. But in case of char it is taken as unsigned.
Why is that ?
Because in xcode IDE char is taken as signed by default.
#include<iostream>
using namespace std;
int main() {
system("clear");
int x;
char y;
cout<<INT_MIN<<" "<<INT_MAX<<endl;
cout<<CHAR_MIN<<" "<<CHAR_MAX<<endl;
return 0;
}
OUTPUT:
-2147483648 2147483647
0 255
| char is an unsigned type on your system, because the people who implemented your system chose that it should be unsigned. This choice varies between systems, and the C++ language specifies that either is allowed. You cannot assume one choice if you wish to write programs that work across different systems.
Note that char, signed char and unsigned char are all three distinct types regardless of whether char is signed or not. By contrast, int and signed int are two names for one and the same type.
|
70,951,670 | 70,955,721 | Using Constructor v/s static method for basic linked list | I've tried implementing a basic linked list in my first try I implemented a static method (insert) for inserting data and pointer to the next element like shown below:
#include <iostream>
using namespace std;
class Node{
public:
int data = NULL;
Node* next = nullptr;
Node(){}
static void insert(int data, Node* next,Node* obj){
obj->data = data;
obj->next = next;
}
static void printList(Node* n){
while(n != nullptr){
cout << n->data << " ";
n = n->next;
}
}
};
int main()
{
Node* head = nullptr;
Node* second = nullptr;
Node* third = nullptr;
head = new Node();
second = new Node();
third = new Node();
//via static method
Node::insert(1,second,head);
Node::insert(2,third,second);
Node::insert(3,nullptr,third);
Node::printList(head);
delete head;
delete second;
delete third;
return 0;
}
it's working fine as I expect (getting output as 1 2 3), but when I implement it using
constructors like show below:
#include <iostream>
using namespace std;
class Node{
public:
int data = NULL;
Node* next = nullptr;
Node(){}
Node(int data, Node* next){
this->data = data;
this->next = next;
}
static void printList(Node* n){
while(n != nullptr){
cout << n->data << " ";
n = n->next;
}
}
};
int main()
{
Node* head = nullptr;
Node* second = nullptr;
Node* third = nullptr;
//via constructors.
head = new Node(1,second);
second = new Node(2,third);
third = new Node(3,nullptr);
Node::printList(head);
delete head;
delete second;
delete third;
return 0;
}
I am getting the output as 1 0. When I call constructor from third to head it's working fine (by that I mean)
third = new Node(3,nullptr);
second = new Node(2,third);
head = new Node(1,second);
Kindly explain why is it behaving like that.
Note: I am a beginner in programming.
| Let's inline insert:
Node::insert(x, a, b) is equivalent to
b->data = x;
b->next = a;
Thus,
Node::insert(1,second,head);
Node::insert(2,third,second);
Node::insert(3,nullptr,third);
is equivalent to
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = nullptr;
Now head->next points to the same node as second points to, and second->next to the same node as third - you could also write
head->next = second;
head->data = 1;
head->next->next = third;
head->next->data = 2;
head->next->next->next = nullptr;
head->next->next->data = 3;
In the failing case, second does not keep pointing to the node you linked first to; it points to a new Node.
Since you assign new values to second and third, it is equivalent to
head = new Node(1,second);
Node* fourth = new Node(2,third);
Node* fifth = new Node(3,nullptr);
and now you see pretty much immediately why it doesn't work.
You could also draw a "boxes and pointers" diagram.
(Beginners are very reluctant to do this. Don't be. It's much faster than debugging.)
Let's look at the failure:
head = new Node(1, second);
head second
| |
v v
+---+ +---+
| -------->| X |
+---+ +---+
then
second = new Node(2,third);
head second third
| | |
v v v
+---+ +---+ +---+ +---+
| -------->| X | | -------->| X |
+---+ +---+ +---+ +---+
Now the node that head->next points to is different from the one second points to - it still points to the default-initialized Node you crated first.
While part of the working one looks like:
second = new Node(2, third);
second third
| |
v v
+---+ +---+
| -------->| X |
+---+ +---+
first = new Node(1,second);
head second third
| | |
v v v
+---+ +---+ +---+
| -------->| -------->| X |
+---+ +---+ +---+
Now, if you don't do this in a "as small steps as possible" fashion, your working constructor code could be written
Node* third = new Node(3,nullptr);
Node* second = new Node(2,third);
Node* head = new Node(1,second);
but the broken one won't compile when you write it like that, and you can spot that there is a dependency problem even without compiling:
Node* head = new Node(1,second); // second is undeclared
Node* second = new Node(2,third); // third is undeclared
Node* third = new Node(3,nullptr);
which is yet another reason to get comfortable with taking bigger steps.
|
70,951,808 | 70,951,846 | Example of useful downcast with static_cast which does not produce undefined behaviour | I am wondering about a short code example of an application of downcast via static_cast, under conditions where there is no undefined behaviour.
I have looked around and I found quite a few texts (posts, Q&A, etc.) referring to fragments of the standard, explaining, etc.
But I found no examples that illustrate that (and that surprises me).
Could anyone provide one such example?
| A very basic example:
class Animal {};
class Dog : public Animal {};
void doSomething() {
Animal *a = new Dog();
Dog *d = static_cast<Dog*>(a);
}
A more contrived example:
class A { public: int a; };
class B : public A {};
class C : public A {};
class D : public B, public C {};
void doSomething() {
D *d = new D();
int bValue = static_cast<B*>(d)->a;
int cValue = static_cast<C*>(d)->a;
// This does not work because we have two a members in D!
// int eitherValue = d->a;
}
There are also countless other cases where you know the actual type type of the instance due to some flags or invariants in your program. However, many sources recommend preferring dynamic_cast in all cases to avoid errors.
|
70,952,369 | 70,952,411 | How did this loophole around const member function worked? | In the below code we try to multiply each element's data in the list by 2 and assign it. But the apply function is a const function therefore should not be able to change the values of member fields. Output for the fifth line in main is
6
4
2
2
4
So code below succeeds in changing the values as intended and I can't figure out why.
#include <iostream>
#include <list>
#include <string>
using std::ostream;
using std::cout;
using std::endl;
template<class E> class MyList {
class Node {
friend class MyList<E>;
E data;
Node* next = nullptr;
}; // end of class Node
Node* head = new Node;
Node* tail = head;
MyList(const MyList&) = default;
public:
MyList() = default;
MyList& operator=(const MyList&) = delete;
void push_front(const E& data) {
Node* node = new Node;
node->data = data;
node->next = head->next;
head->next = node;
if(head->next == nullptr) tail = node;
}
void push_back(const E& data) {
if(head->next == nullptr) {
push_front(data); return;
}
MyList temp(*this);
temp.head = temp.head->next;
temp.push_back(data);
temp.head = nullptr;
}
~MyList() {
Node *node = head, *next;
while(node != nullptr) {
next = node->next;
delete node;
node = next;
}
}
template<class Function>
void apply (Function f) const {
Node* node = head->next;
while(node != nullptr) {
f(node->data);
node = node->next;
}
}
};
int main() {
MyList<int> m1;
m1.push_back(3);
for(int i = 1; i <= 2; ++i) m1.push_front(i);
for(int i = 1; i <= 2; ++i) m1.push_back(i);
m1.apply(
[](auto& val){ val *= 2;}
);
m1.apply(
[](const auto& val){cout << val << endl;}
);
return 0;
}
| The key is logical vs bitwise constness. The head data member is a non-const pointer to non-const Node: the const correctness of the apply member function is bitwise constness:
you cannot change what the head data member (pointer) points to from a const-qualified member function.
You can, however, mutate the Node object that it points to.
|
70,952,498 | 70,982,564 | Direct2D Error NO_HARDWARE_DEVICE When Injecting Dll Into Another Process | I have a native target application that renders something by using Direct3D11. I want to extend the functionality of the target by injecting a DLL and hooking some APIs(not important to mention but it is XInputGetState). When DLL is injected, it also creates a window and provides some useful information. To render the information in the window, I use Direct2D, but after injecting the DLL, in another process's address space, calling the ID2D1Factory::CreateHwndRenderTarget fails with the error code D2DERR_NO_HARDWARE_DEVICE and doesn't create the ID2D1HwndRenderTarget object. The Factory object is created successfully and it is not NULL.
When I change the project type from Dynamic Link Library(.dll) to Application(.exe) and the entry point from DllMain to main and run it as a separate console application, the ID2D1Factory::CreateHwndRenderTarget succeeds.
I think that the problem causes by the existence of a created Direct3D11 Device already, but I am not sure.
Is there documentation about that? How can I solve the issue?
| Put directly the D2D creating function into new thread by CreateThread in DllMain.
|
70,952,646 | 70,962,382 | Why is C++23 stacktrace_entry different from source_location? | class stacktrace_entry {
public:
string description() const;
string source_file() const;
uint_least32_t source_line() const;
/* ... */
};
struct source_location {
// source location field access
constexpr uint_least32_t line() const noexcept;
constexpr uint_least32_t column() const noexcept;
constexpr const char* file_name() const noexcept;
constexpr const char* function_name() const noexcept;
/* ... */
};
They serve basically the same purpose, why do they have differences, specifically no column in stacktrace_entry, or not even share the same class?
| The answers from the proposal author.
Regarding returning std::string:
As it is stated in P0881R7: "Unfortunately this is a necessarity on some platforms, where getting source line requires allocating or where source file name returned into a storage provided by user."
Regarding column:
Most popular solutions for non-Windows platforms do not provide a source_column(). At the moment std::stacktrace is a minimal subset of abilities of all platforms, so the column is missing. This could be changed later, the addition seems quite simple for C++ standardization.
|
70,952,653 | 70,952,935 | C++ program where user will input names and decide which gender (M/F) to show | Using c++ I need to make a program using map in c++ where the gender (M or F) is the key of 6 input names, and then it will ask the user to choose what gender to display (Male or Female). I am stuck with this, I do not know what to do next.
#include <iostream>
#include <set>
using namespace std;
int main(){
set<pair<string,string>> s;
set<pair<string,string>>::iterator itr;
string name;
string gender;
cout<<"Enter 6 names with genders : "<<endl;
for(int a=1; a<=6; a++){
cin>>gender;
getline(cin, name);
s.insert({name,gender});
}
cout<<endl;
cout<<"Enter the gender(M/F): ";
cin>>gender;
for (itr = s.begin(); itr != s.end(); itr++) {
if(itr->second==gender)
cout<<" "<<itr->first<<" "<<itr->second<<endl;
}
cout << endl;
return 0;
}
| You can try "set" instead of map.
#include <iostream>
#include <set>
using namespace std;
int main(){
set<pair<char,string>> s;
cout<<"Enter 6 gender and name : "<<endl;
char gender; string name;
for(int a=1; a<=6; a++){
cin >> gender; getline(cin, name);
s.insert({gender,name});
}
set<pair<char,string>>::iterator itr;
for(itr = s.begin(); itr!=s.end(); itr++){
cout << itr->first << " " << itr->second << endl;
}cout << endl;
return 0;
}
|
70,953,123 | 70,953,518 | Envoy access logs format validation | We are using envoy access logs
https://www.envoyproxy.io/docs/envoy/latest/configuration/observability/access_log/usage , does envoy validate the fields that are passed to the access logs, e.g. the field format.
I ask it from basic security reason to verify that if I use for example %REQ(:METHOD) I will get a real http method like get post etc and not something like foo. or [%START_TIME%] is in time format and I will not get something else...
I think it's related to this envoy code
https://github.com/envoyproxy/envoy/blob/24bfe51fc0953f47ba7547f02442254b6744bed6/source/common/access_log/access_log_impl.cc#L54
I ask it since we are sending the data from the access logs to another system and we want to verify that the data is as its defined in the access logs and no one will change it from security perspective.
like ip is real ip format and path is in path format and url is in url format
| I'm not sure I understand the question. Envoy doesn't have to validate anything as it is generating those logs. Envoy is HTTP proxy who receives the request and does some routing/rewriting/auth/drop/.. actions based on the configuration (configured by virtualservice / destinationrule / envoyfilter if we're talking about istio). After the action it generates the log entry and fills the fields with details about original request and actions taken.
Also there is nothing like 'real' http method. HTTP method is just a string and it can hold any value. Envoy is just the proxy who sits between client and application and passes the requests (unless you explicitly configure it i.e. drop some method).
It depends on application who receives the method how it's treated. GET/POST/HEAD are commonly associated with standard HTTP and static pages. PUT/DELETE/PATCH are used in REST APIs. But nothing prevents you to develop application who will accept 'FOOBAR' method and runs some code over it.
|
70,953,345 | 70,953,871 | Can I extern the entire namespace? | Is there a method to declare a namespace with the extern modifier so that the namespace's entire content is externally linked?
| You seem to be asking two questions. One regarding external linkage and one regarding the extern specifier.
Regarding the linkage, there is not really a need for such a syntax.
External linkage is already the default at namespace scope, whether in the global namespace or another namespace, except for const non-template non-inline variables and members of anonymous unions. (https://en.cppreference.com/w/cpp/language/storage_duration#internal_linkage)
So the other way around, syntax to make all names in a namespace have internal linkage, is more likely to be required and this is possible with unnamed namespaces
namespace {
//...
}
in which all declared names have internal linkage.
Regarding the extern specifier used to turn a variable definition into just a declaration at namespace scope or to give it external linkage explicitly, I am not aware of any syntax to apply it to a whole namespace. You will have to specify it explicitly on each variable.
|
70,953,755 | 71,025,516 | Subset columns of sparse eigen matrix | I want to take subset columns of some sparse matrix (column-major)
As far as i know there are indexing stuff in Eigen.
But i cannot call it for sparse matrix:
Eigen::SparseMatrix<double> m;
std::vector<int> indices = {1, 5, 3, 6};
// error: type 'Eigen::SparseMatrix<double>' does not provide a call operator
m(Eigen::all, indices);
Is there are any workaround?
UPD1
Explicitly specified that columns can be in arbitrary order.
| The SparseMatrix actually does not provide any operator(), so this cannot be done.
EDIT: The following was aimed at an older version of the question.
In case your actual use case also has the property that the columns you want to access are adjacent you can instead use
SparseMatrix<double,ColMajor> m(5,5);
int j = 1;
int number_of_columns=2;
m.middleCols(j,number_of_columns) = ...;
There are also m.leftCols(number_of_columns) and m.rightCols(number_of_columns)
These are even writable, because the matrix is column-major.
All other block expressions are defined but read-only, see the corresponding Sparse Matrix documentation.
EDIT: To answer the updated question:
I guess you won't be able to avoid copying. With copying it can be done like this (not tested)
Eigen::SparseMatrix<double> m;
std::vector<int> indices = {1, 5, 3, 6};
Eigen::SparseMatrix<double> column_subset(m.rows(),indices.size());
for(int j =0;j!=column_subset.cols();++j){
column_subset.col(j)=m.col(indices[j]);
}
|
70,954,015 | 71,044,310 | Can I use IDXGIFactory2::CreateSwapChainForHwnd for directx 11.0 | As I undrestood, IDXGIFactory2::CreateSwapChainForHwnd was added in DXGI 1.2 API so if the method D3D11CreateDevice will return pFeatureLevel equal D3D_FEATURE_LEVEL_11_0 we able to use only DXGI 1.1 API, therefore we should call IDXGIFactory::CreateSwapChain instead of IDXGIFactory2::CreateSwapChainForHwnd. Am I right?
HRESULT D3D11CreateDevice(
[in, optional] IDXGIAdapter *pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
[in, optional] const D3D_FEATURE_LEVEL *pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
[out, optional] ID3D11Device **ppDevice,
[out, optional] D3D_FEATURE_LEVEL *pFeatureLevel,
[out, optional] ID3D11DeviceContext **ppImmediateContex
| My guess here is that your customer is running Windows 7, and is missing the DirectX 11.1 Runtime which is installed by the KB2670838 update.
See Microsoft Docs, as well as this blog post and this follow-up post.
It's probably best to just tell customers you require KB 2670838 if they are using Windows 7. Supporting the DirectX 11.0 Runtime is certainly possible, but there are a number of quirks and you have to use DXGI 1.1 interfaces for the swapchain. See this blog post.
KB 2670838 is also available from Microsoft Download as MSU files if the customer has Internet access issues.
You should recheck the error handling of your application. You should have gotten an error HRESULT when you tried to QueryInterface the IDXGIFactory2 interface if the system only had DirectX 11.0 on it. Remember if a function returns HRESULT, it's not safe to ignore the return value: Use FAILED or SUCCEEDED or a fast-fail like ThrowIfFailed to make sure you hit the failure when it happens and not sometime later.
These days it's best to require Windows 7 Service Pack 1 if you support Windows 7. For example, the last few releases of Visual C++ only support Windows 7 SP1. That said, KB2670838 is not included in the Service Pack 1 package. It's pushed out via Windows Update as a recommended update, but if you have WU turned off or have created a fresh install of even Windows 7 SP1, you can be missing it. Note that KB2670838 doesn't support Windows 7 RTM in any case.
Don't use 'Direct3D Hardware Feature Level' to infer the supported DirectX APIs. It's best to just QueryInterface for the ID3D11Device1 if you want to check after creating the ID3D11Device to see if DirectX 11.1 is present, but a more direct test is to try to QUeryInterface the IDXGIFactory2 interface.
|
70,954,719 | 70,954,798 | why socket is ready to read only after thousands of iterations? | I am writing my http server. I use select function and see that socket is ready to write any time, but can be read only after thousands of iterations. If I use select(Max+1, &rfd, NULL, NULL, NULL), I do not have such problem. Why it is ready to read only after so many iterations?
int iteration = -1;
while (true)
{
iteration++;
FD_ZERO(&rfd);
FD_ZERO(&wfd);
FD_SET(listeningSocket, &rfd);
for (std::set<int>::iterator Iter = servingSockets.begin(); Iter != servingSockets.end(); Iter++)
{
FD_SET(*Iter, &rfd);
FD_SET(*Iter, &wfd);
}
int Max = std::max(listeningSocket, *std::max_element(servingSockets.begin(), servingSockets.end()));
res = select(Max + 1, &rfd, &wfd, NULL, NULL);
if (res <= 0)
continue;
if (FD_ISSET(listeningSocket, &rfd))
{
if ((newSocket = accept(listeningSocket, (struct sockaddr *)&listeningSocketAddr, (socklen_t *)&listeningSocketAddr)) < 0)
continue;
fcntl(newSocket, F_SETFL, O_NONBLOCK);
servingSockets.insert(newSocket);
}
for (std::set<int>::iterator Iter = servingSockets.begin(); Iter != servingSockets.end();)
{
if (FD_ISSET(*Iter, &rfd))
{
std::cout<<"iter in loop: "<<iteration<<std::endl;
int bytes_recvd = recv(*Iter, request, request_buffer_size - 1, 0);
if (bytes_recvd < 0)
{
fprintf(stderr, "error recv\n");
shutdown(*Iter, SHUT_RDWR);
close(*Iter);
servingSockets.erase(*Iter);
continue;
}
request[bytes_recvd] = '\0';
parse_http_request(request, &req);
}
if (FD_ISSET(*Iter, &wfd) && req.path[0] != '\0')
{
send(*Iter, "HTTP/1.1 200 OK\n\n<h1><a href=\"\">external</a><br><a href=\"internal\">internal</a></h1>", 122, 0);
shutdown(*Iter, SHUT_RDWR);
close(*Iter);
Iter = servingSockets.erase(Iter);
continue;
}
Iter++;
}
}
| A socket will always be writable, unless you fill up its buffers.
So select will return immediately for every call, with all the sockets marked as writable.
Only add sockets to the write-set when you actually have something to write to them. And once you have written all you need, then remove them from the set and don't add them back (until the next time you need to write to the socket).
When you don't use the write-set, then select will simply not return until there's a socket active in the read-set.
|
70,954,866 | 70,955,091 | What is the best practice to check if an object is null in C++ | I am working on a simple example. Let s say that I have an object Object my_object and I want to check if the object is null.
Therefore, I instantiate the object:
auto my_object = createMyObject(param_object_1);
The idea, is to check whether the object is null or not. If I am not mistaken (I am really new in C++), I have tried
Check if reference is NULL
I believe this is not an option (even if compiling) since references can never be NULL, so I have discarded it.
EXPECT_TRUE(my_object != NULL);
Check if != to nullptr
My next try has been to check if a pointer to the object is null.
auto my_object_ptr = std::make_shared<Object>(my_object);
EXPECT_TRUE(my_object_ptr != nullptr);
This code also compiles but I am not sure if this is the solution I was looking for. My intentions is to check if the pointer is pointing to a null object.
Is it a valid way to do it? If not, what s the best practise to check if the object is empty?
|
I want to check if the object is null.
Congratulations, your Object object is not null. null is not a possible value for object to be.
A close analog might be to test that it is different to a default-constructed Object, if Object is default-constructable.
EXPECT_TRUE(my_object != Object{})
|
70,955,074 | 70,955,206 | Can't properly insert a pair generated in code into a std::map | I have a weird problem. I have a map in C++ defined like this as private in a class.
std::map<const char *, GameObject *> GameObjects;
I have a function that adds pairs to the map.
void myClass::Add(const char *name, GameObject *object)
{
GameObjects.insert(std::make_pair(name, object));
}
It works fine if I add pairs like this.
m_myClass.Add("Example", new GameObject());
Now, the problem is in the Instantiate function, declared like this.
void myClass::Instantiate(GameObject *object)
{
char *name = (char *)malloc(strlen("New Object ") + 12); // New Object xxxxxxxxxxxx x -> digit
memset(name, 0, strlen("New Object ") + 12); // clear
strcpy(name, "New Object "); // copy the first part
strcpy(name + strlen("New Object "), std::to_string(newObjs++).c_str()); // copy the number part
printf("Creating %s", name);
Add(name, object); // add it to our map
}
If I iterate over every item from the map, the pair appears to exist and works indexing it but when I index it manually (GameObjects["pairName"]) the program crashes with a segmentation fault message. Also GameObjects.contains("pairName") returns false even if I added the pair with that name.
I use GCC 11.2.0 on Ubuntu with the C++20 standard enabled.
| A string literal has a different pointer value to a return value of malloc. The map will do lookup with std::less<const char *> which compares pointer values, it does not compare text.
Use std::string, and don't use malloc or owning raw pointers.
std::map<std::string, std::unique_ptr<GameObject>> GameObjects;
void myClass::Add(std::string name, std::unique_ptr<GameObject> object)
{
GameObjects.emplace(std::move(name), std::move(object));
}
void myClass::Instantiate(std::unique_ptr<GameObject> object)
{
std::string name{ "New Object " };
name += std::to_string(newObjs++)
std::cout << "Creating " << name;
Add(std::move(name), std::move(object));
}
|
70,955,759 | 70,955,836 | How to get around calling base class constructor from derived class with the same arguments? | I want to use a base object that defines an "interface" and then have derived objects implement it. Every object is initialized with its name which is always the same process: Writing to a member "name_" with parameter passed to the constructor. I want to have derived objects behave exactly the same way as the base object in that regard, so every derived object should write to its name varialbe. However, the problem is that I would need to define an extra constructor in every derived object that writes to the name variable which is cumbersome. The following example does not compile because of this reason. Is there any way around this or is inheritance even the right approach (please feel free to suggest otherwise)?
Non-compiling code (shows what I want to do):
#include <iostream>
class A {
const std::string name_;
public:
A(const std::string name) : name_(name) { std::cout << "creation of object " << name_ << "; this name = " << this->name_ << '\n'; }
};
class B : public A {
// const std::string name_; -- we do not even need this because "name_" also exists for object B.
// C++ misses its constructor here :') - I don't
};
int main()
{
A obj_a{ "A" };
B obj_b{ "B" };
}
Associated error(s):
source>:20:18: error: no matching function for call to 'B::B(<brace-enclosed initializer list>)'
20 | B obj_b{ "B" };
| ^
<source>:12:7: note: candidate: 'B::B(const B&)'
12 | class B : public A {
| ^
<source>:12:7: note: no known conversion for argument 1 from 'const char [2]' to 'const B&'
<source>:12:7: note: candidate: 'B::B(B&&)'
<source>:12:7: note: no known conversion for argument 1 from 'const char [2]' to 'B&&'
ASM generation compiler returned: 1
<source>: In function 'int main()':
<source>:20:18: error: no matching function for call to 'B::B(<brace-enclosed initializer list>)'
20 | B obj_b{ "B" };
| ^
<source>:12:7: note: candidate: 'B::B(const B&)'
12 | class B : public A {
| ^
<source>:12:7: note: no known conversion for argument 1 from 'const char [2]' to 'const B&'
<source>:12:7: note: candidate: 'B::B(B&&)'
<source>:12:7: note: no known conversion for argument 1 from 'const char [2]' to 'B&&'
| You may use a using-declaration to
Using-declaration
[...] introduce base class members into derived class definitions.
[...]
Inheriting constructors
If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class.
If overload resolution selects an inherited constructor, it is accessible if it would be accessible when used to construct an object of the corresponding base class: the accessibility of the using-declaration that introduced it is ignored.
as such:
class B : public A {
using A::A;
};
Note the highlight that the accessibility of the using-declaration itself is ignored, meaning using A::A in the example needn't the be placed under public accessibility - what matters is the accessibility of the inherited constructors in B.
|
70,956,681 | 70,956,856 | Function for a specific numeric sequence without any parameters | I got an university task which i am totally stuck on. Normally I wouldn't post about it here, but none of my colleagues has any idea how to solve it.
The Task:
Design an algorithm "NEXT", which delivers the subsequent value of the numeric sequence {0,3,5,6,9,10,12,15,18,20,21,...} as function value whenever it is called. The algorithm must not use parameters or global variables or vectors.
I have to implement it in C++ (which shouldn't be too much of an issue for me). I just have no idea how. I can't find any form of rule for the number sequence. And i am kinda stuck on the part where i have to return the next value of the sequence without giving any parameters to the function.
It would be awesome if someone could help me out here :)
(FYI, i had to translate the task and i hope I didn't make any critical Errors... Here it is again in the original languge german:
Entwerfen Sie einen Algorithmus N E X T, der bei jedem Aufruf den
jeweils nachsten Wert der Folge {0,3,5,6,9,10,12,15,18,20,21,...} als Funktionswert liefert.
Der Algorithmus darf weder Parameter haben noch globale Variablen oder Vektoren verwenden.)
| The sequence consists in all multiples of 3 or 5, in increasing order.
|
70,956,747 | 70,969,314 | Build tesseract as DLL Dynamic link library | I'm using this .NET wrapper https://github.com/charlesw/tesseract and I wanted to update the included tesseract and leptonica DLLs but after a long google search I was not able to generate them from the original tesseract and leptonica github repositories.
I already ask on the charlesw repository but did not get any reply (https://github.com/charlesw/tesseract/issues/486).
Any help on how to build the DLLs is much appreciated.
Thanks!
https://github.com/tesseract-ocr/tesseract
https://github.com/danbloomberg/leptonica
Answer : (thank you user898678 for the link)
Using bucket401 blog post tutorial I extracted the required part to generate:
leptonica-X.XX.X.dll
tesseract.exe
tesseractXX.dll
and created this buildTesseractLeptonica.bat :
mkdir buildTesseractLeptonica
cd buildTesseractLeptonica
mkdir bin
set INSTALL_DIR=%cd%
set PATH=%PATH%;%INSTALL_DIR%\bin
call "c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" x64
set INCLUDE=%INCLUDE%;%INSTALL_DIR%\include
set LIBPATH=%LIBPATH%;%INSTALL_DIR%\lib
set TESSDATA_PREFIX=%INSTALL_DIR%\share\tesseract\tessdata
git clone --depth 1 https://github.com/DanBloomberg/leptonica.git
cd leptonica
cmake -Bbuild -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DCMAKE_PREFIX_PATH=%INSTALL_DIR% -DBUILD_PROG=OFF -DSW_BUILD=OFF -DBUILD_SHARED_LIBS=ON
cmake --build build --config Release --target install
cd ..
git clone --depth 1 https://github.com/tesseract-ocr/tesseract.git
cd tesseract
cmake -Bbuild -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DCMAKE_PREFIX_PATH=%INSTALL_DIR% -DLeptonica_DIR=%INSTALL_DIR%\lib\cmake -DBUILD_TRAINING_TOOLS=OFF -DSW_BUILD=OFF -DOPENMP_BUILD=OFF -DBUILD_SHARED_LIBS=ON
cmake --build build --config Release --target install
cd ..
bucket401 blog post link: https://bucket401.blogspot.com/2021/03/building-tesserocr-on-ms-windows-64bit.html
| There are several tutorials you can follow:
https://bucket401.blogspot.com/2021/03/building-tesserocr-on-ms-windows-64bit.html
http://spell.linux.sk/building-minimalistic-tesseract
https://github.com/tesseract-ocr/tessdoc/blob/main/Compiling.md#windows
|
70,956,820 | 72,649,815 | How can I use CMake on command line? - Windows | I want to run CMake on a Windows machine on the command line. The problem is that using Visual Studio as the generator works fine, but when using Ninja, CMake cannot find the specified compiler (cl.exe). I have been able to get around this by calling vcvarsall.bat x64 on the command line before I run the cmake command, but shouldn't there be an easier way? Microsoft's documentation seems to suggest that this is the proper way.
Is there a way to invoke vcvarsall.bat in a CMakePresets.json file? Alternatively, since I am using VS Code, is there a way to have presets for VS Code so I can select what development enviroment I want? Sort of like a presets.json file, but for VS Code?
I have tried adding cl.exe to my PATH, but whenever doing this, there are other environment variables that also need set up.
I should also mention that none of this setup process needs to be done on Linux. Is there any way for Windows to always be able to access the necessary c++ files?
Finally, my motivation for all of this is to eventually use Intel's c++ compiler (icx.exe). Thank you for your time and suggestions.
Here is what the not working configuration in my CMakePresets.json file looks like:
{
"name": "Ninja - MSVC",
"displayName": "Ninja - MSVC",
"description": "Ninja with MSVC compiler",
"binaryDir": "${sourceDir}/_build",
"generator": "Ninja",
"cacheVariables": {"CMAKE_C_COMPILER": "cl", "CMAKE_CXX_COMPILER": "cl"},
"condition": {"type": "equals", "lhs": "${hostSystemName}", "rhs": "Windows"},
"vendor": {
"microsoft.com/VisualStudioSettings/CMake/1.0": {
"hostOS": "Windows"
}
}
}
| I have found several workflows to simplify this process for me:
I found that the comment by Alan Birtles is the most user friendly approach to improving my workflow. The recommendation was to use the CMake Tools extension for VS Code which easily scans your system for compilers and you can use options in the bottom bar of VS Code to set up your project. On top of this, there are a bunch of settings for the extension in VS Code to customize the tool to your needs. This is by far the easiest to use, and it is the easiest to implement across different platforms and users.
The second option was to run CMake directly in a Visual Studio Developer Command Prompt, but the disadvantage of this approach compared to the first is that you still have to type out your CMake commands.
The final option is to run vcvarsall.bat x64 on startup of VS Code with a tasks.json file, but this option requires that you specify the path of the bat file, which isn't always portable.
|
70,957,213 | 70,957,616 | How can I add backspace? | My professor is asking me to make a program that asks for email and password that while the user is typing its password the characters will be changed into *, My problem is whenever I press backspace it continues to print * and not deleting it. Please help me how this program will delete the previous character and not add * when I press backspace. Thanks
You can also add a tip on how I can improve my programming
CODE
Here is the code that I'm working with
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
int main()
{
string pass = "";
char password;
string email;
string name;
name = "Mon Alvin Rafael";
cout << " Enter Email: ";
cin >> em;
cout << " Enter Password: \b";
password = _getch();
while (ch != 13) {
//character 13 is enter
pass.push_back(password);
cout << '*';
ch = _getch();
}
if (pass == "password1234" && email == "email1234")
{
cout << "\n Welcome " << name << endl;
return main();
}
else
{
cout << "\n Invalid Password or Email" << endl;
return main();
}
}
| You can check if the user presses the backspace (character code 8) and if the do print the backspace character '\b' to move the cursor back by one, followed by ' ' to overwrite the '*' and then another backspace character the move the cursor back again. Of course making sure to also delete the last character from the password string.
string pass = "";
char ch;
string email;
string name;
name = "Mon Alvin Rafael";
cout << " Enter Email: ";
cin >> email;
cout << " Enter Password: \b";
ch = _getch();
while (ch != 13) {
if (ch == 8) {
// backspace was pressed
if (pass.length()) {
cout << "\b \b";
pass.pop_back();
}
ch = _getch();
continue;
}
//character 13 is enter
pass.push_back(ch);
cout << '*';
ch = _getch();
}
|
70,957,598 | 70,957,700 | disable code from compiling for non integral types | #include <iostream>
#include <type_traits>
#include <math.h>
template<typename T>
void Foo(T x)
{
if(std::is_integral<T>::value)
{
rint(x);
}
else
{
std::cout<<"not integral"<<std::endl;
}
}
int main()
{
Foo("foo");
return 0;
}
Does not compile because there is no suitable rint overload for const char*, but rint will never be invoked with const char* because it's not an integral type. How can I inform the compiler about this
| In c++17 you could use if constexpr instead of if and it would work.
In c++14 you could specialize a struct to do what you want
template<class T, bool IsIntegral = std::is_integral<T>::value>
struct do_action
{
void operator()(T val) { rint(val); }
};
template<class T>
struct do_action<T, false>
{
void operator()(T val) { std::cout << "Not integral\n"; }
};
template<class T>
void Foo(T x)
{
do_action<T>()(x);
}
|
70,958,035 | 70,971,174 | short_alloc with _GLIBCXX_FULLY_DYNAMIC_STRING disabled | I wonder if anyone has run Howard Hinnant's short_alloc when libglibc++ has _GLIBCXX_FULLY_DYNAMIC_STRING=1. I am stuck on how to workaround this error:
/usr/include/c++/9/bits/basic_string.tcc:596:30: error: no matching function for call to 'myapp::short_alloc<char, 131072>::short_alloc()'
596 | if (__n == 0 && __a == _Alloc())
| ^~~~~~~~
https://godbolt.org/z/z79K584EE
| The point of this allocator is to use stack memory. arena_type is used to reserve some stack memory for the allocator.
The allocator instance needs to know which arena to use. Therefore you cannot default-construct the allocator and by extension the string.
You always need to provide a reference to the arena to use when constructing a new string, e.g.:
using alloc = short_alloc<char, 1024, alignof(char)>;
using mystring = std::basic_string<char, std::char_traits<char>, alloc>;
alloc::arena_type a;
mystring str(a);
str = "Hello world!";
std::cout << str;
If you are wondering why it is necessary to define the area variable separately, rather than it just being a part of the allocator object: This is because it is not possible to do the latter and get an allocator conforming to the standard requirements for an allocator. See this question.
|
70,958,162 | 70,958,498 | SFINAE detection: substitution succeeds when compilation fails | I wrote a simple SFINAE-based trait to detect whether a class has a method with a specific signature (the back story is that I am trying to detect whether a container T has a method T::find(const Arg&) - and if yes, then store a pointer to this method).
After some testing I discovered a case where this trait would give a false positive result - if T defines the method as a template but definition compiles not for all possible Ts. This is best demonstrated with an example:
#include <iostream>
#include <string>
#include <vector>
#include <type_traits>
using namespace std;
// HasFooWithArgument is a type trait that returns whether T::foo(const Arg&) exists.
template <typename T, typename Arg, typename = void>
inline constexpr bool HasFooWithArgument = false;
template <typename T, typename Arg>
inline constexpr bool HasFooWithArgument<T, Arg, std::void_t<decltype(std::declval<const T&>().foo(std::declval<const Arg&>()))>> = true;
// Below are the test cases. struct E is of the most interest.
struct A {};
struct B {
void foo(int x) const {}
};
struct C {
void foo(int x) const {}
void foo(const std::string& x) const {}
};
struct D {
template <typename T>
void foo(const T& x) const {}
};
struct E {
// Any T can be substituted (hence SFINAE "detects" the method)
// However, the method compiles only with T=int!
// So effectively, there is only E::foo(const int&) and no other foo methods...
template <typename T>
void foo(const T& x) const {
static_assert(std::is_same_v<T, int>, "Only ints are supported");
}
};
int main()
{
cout << std::boolalpha;
cout<<"A::foo(int): " << HasFooWithArgument<A, int> << "\n";
cout<<"B::foo(int): " << HasFooWithArgument<B, int> << "\n";
cout<<"C::foo(int): " << HasFooWithArgument<C, int> << "\n";
cout<<"C::foo(string): " << HasFooWithArgument<C, std::string> << "\n";
cout<<"C::foo(std::vector<int>): " << HasFooWithArgument<C, std::vector<int>> << "\n";
cout<<"D::foo(string): " << HasFooWithArgument<D, std::string> << "\n";
cout<<"E::foo(int): " << HasFooWithArgument<E, int> << "\n";
cout<<"E::foo(string): " << HasFooWithArgument<E, std::string> << "\n";
E e;
e.foo(1); // compiles
// e.foo(std::string()); // does not compile
return 0;
}
The above prints:
A::foo(int): false
B::foo(int): true
C::foo(int): true
C::foo(string): true
C::foo(std::vector<int>): false
D::foo(string): true
E::foo(int): true
E::foo(string): true
Unfortunately, this last case is my main target: as I mentioned above, I am doing this to detect container find methods and they are usually defined as templates to support heterogeneous lookup.
In other words, std::set<std::string, std::less<>> is where my detection gives false positives as it returns true for any argument type.
Thanks in advance!
| The issue you're describing is not due to the fact that SFINAE doesn't work properly with function templates (it does). It has to do with the fact that SFINAE can't detect whether a function body is well-formed.
Your approach should work just fine when it comes to detecting that std::set<std::string> does not have a find member that takes a std::string_view argument. This is because the templated find member does not participate in overload resolution unless the set has a transparent comparator. Since std::set<std::string> doesn't have a transparent comparator, its find function will only accept types that are implicitly convertible to std::string; any attempt to pass any other type will result in an overload resolution failure, which will be detected by SFINAE just like any other case of an argument type mismatch.
Where your approach won't work is with something like std::set<std::string, std::less<>> and trying to call find with an argument type of say, int. In this case the detection will succeed because the find template is unconstrained, but then compilation will fail later on if you try to actually call find with an int argument, because somewhere in the body, it will try to call std::less<> with types that can't be compared with each other (std::string and int).
Colloquially, we say that a function or a class that makes it possible to detect using SFINAE whether it, itself, would be well-formed, is "SFINAE-friendly". In that sense, std::set::find fails to be SFINAE-friendly. To make it SFINAE-friendly, it would have to guarantee that an overload resolution failure would occur if you tried to call it with a type that isn't comparable using the specified transparent comparator.
When something is not SFINAE-friendly, the only workaround is to special-case it: in other words, you have to put in your code a special case that makes detection fail for std::set::find in this case, by checking explicitly whether the comparator accepts the argument type. (std::less<> is SFINAE-friendly: it does the overload resolution in the (explicitly specified) return type.)
|
70,958,269 | 70,960,120 | Disable CTS flow control on windows COM port | I am using SetCommState to configure a COM port.
if (!BuildCommDCBA(
"baud=9600 parity=N data=8 stop=1",
&dcbSerialParams))
return;
SetCommState(myCOMHandle, &dcbSerialParams);
This appears to enable the CTS flow control, which my hardware does not support
_COMMCONFIG cfg;
DWORD sz = sizeof(cfg);
if (!GetCommConfig(
myCOMHandle, // Handle to the Serial port
&cfg,
&sz))
std::cout << "GetCommConfig FAILED\n";
DCB dcb = cfg.dcb;
std::cout << "\nBaudRate " << dcb.BaudRate
<< "\nfBinary " << dcb.fBinary
<< "\nfParity " << dcb.fParity
<< "\nfOutxCtsFlow " << dcb.fOutxCtsFlow ...
outputs
BaudRate 9600
fBinary 1
fParity 0
fOutxCtsFlow 1
I have tried using
"baud=9600 parity=N data=8 stop=1 octs=off"
but this gives the same result.
I have also tried over-writing the output from BuildCommDCBA
dcbSerialParams.fOutxCtsFlow = 0;
if (!BuildCommDCBA(
"baud=9600 parity=N data=8 stop=1",
&dcbSerialParams))
return;
dcbSerialParams.fOutxCtsFlow = 0;
SetCommState(myCOMHandle, &dcbSerialParams);
but this also gives the same result.
The documentation for BuildCommDCBA says this
There are older and newer forms of the mode syntax. The BuildCommDCB
function supports both forms. However, you cannot mix the two forms
together.
The newer form of the mode syntax lets you explicitly set the values
of the flow control members of the DCB structure. If you use an older
form of the mode syntax, the BuildCommDCB function sets the flow
control members of the DCB structure,
This certainly seems to have something to do with my problem. However I cannot find a description of the newer and older forms of the mode syntax. I have looked at this.
Can I assume I am using the newer from? Why is the fOutxCtsFlow being set? How can I force it to unset?
| According to MSDN:
The BuildCommDCB function adjusts only those members of the DCB structure that are specifically affected by the lpDef parameter...
So you need to make sure all the other fields have acceptable values. The simplest way is to just initialize with
DCB dcbSerialParams = { 0 };
This should disable all flow control by setting all pertinent values to FALSE or 0. As long as your string sets all the other important stuff (baud rate, parity, stop bits, and data size) this should be ok. In particular, you will get:
fBinary = FALSE;
fNull = FALSE;
fErrorChar = FALSE;
fParity = FALSE;
fRtsControl = RTS_CONTROL_DISABLE;
fOutxCtsFlow = FALSE;
fOutX = FALSE;
fInX = FALSE;
fDtrControl = DTR_CONTROL_DISABLE;
fOutxDsrFlow = FALSE;
Another option is to initialize the fields by calling one of
GetCommConfig() - Retrieves the current configuration of a communications device.
GetDefaultCommConfigA() - Retrieves the default configuration for the specified communications device.
GetCommState() - Retrieves the current control settings for a specified communications device.
|
70,958,419 | 70,958,764 | Function pointer which accepts both with and without noexcept | I have some utility code that I've been using for years to safely call the ctype family of functions, it looks like this:
template<int (&F)(int)>
int safe_ctype(unsigned char c) {
return F(c);
}
And is used like this:
int r = safe_ctype<std::isspace>(ch);
The idea being that it handles the need to cast the input int to an unsigned value for you in order to prevent undefined behavior. The specifics of this function is somewhat irrelivant though. Here's my question:
Now that in C++17 and later, noexcept is part of the type system, this is a compile error! Because all of the ctype functions are now noexcept.
EDIT: The above sentence is incorrect. the ctype family of functions are not noexcept. I was however getting a compiler error in gcc < 11.2. https://godbolt.org/z/cTq94q5xE
The code works as expected (despite being technically not allowed due to these functions not being addressable) with the latest versions of all 3 major compilers.
I can of course change my function to look like this:
template<int (&F)(int) noexcept>
int safe_ctype(unsigned char c) noexcept {
return F(c);
}
But now it doesn't work when compiled as C++11 or C++14. So I end up having to do something like this:
#if __cplusplus >= 201703L
template<int (&F)(int) noexcept>
int safe_ctype(unsigned char c) noexcept {
return F(c);
}
#else
template<int (&F)(int)>
int safe_ctype(unsigned char c) {
return F(c);
}
#endif
Which is getting increasingly complex for such a simple task. So is there a way to make the function pointer:
valid for C++11 - C++20
Accept both noexcept and non-noexcept when in C++17+
?
I tried doing something like this:
template<class F>
int safe_ctype(unsigned char c) noexcept {
return F(c);
}
In the hopes that it would accept "anything", but sadly, no go.
Thoughts?
|
Now that in C++17 and later, noexcept is part of the type system, this is a compile error! Because all of the ctype functions are now noexcept.
It is not a compile error. Pointers to noexcept functions are implicitly convertible to pointers to potentially throwing functions, and thus the template accepting a pointer to potentially throwing functions works with both potentially throwing and noexcept functions. Only caveat is that the noexceptedness information is lost and might not be used for optimisation purposes.
Hence, the original solution satisfies both points 1. and 2.
Another problem pointed out in the comments is that the standard library functions (std::isspace) that you intend to use are not designated "addressable". Hence the behaviour of the program is unspecified (possibly ill-formed) due to forming a pointer to them.
To wrap such callable, you could use a lambda instead of a function pointer. But that makes the template itself obsolete since you can change the argument type of the lambda directly:
auto safe_isspace = [](unsigned char c){ return std::isspace(c); };
int r = safe_isspace(ch);
Though we no longer need to pass this into a template, so the same can be achieved with a plain function:
int // or bool?
safe_isspace(unsigned char c) noexcept // ...
Since this involves a bit of identical boilerplate for multiple functions, this is a good candidate for meta-programming.
|
70,958,920 | 70,959,877 | Storing template abstract classes in std::vector | I am trying to translate some Java code into C++ and I am having some trouble with the type system.
I have a interface/pure virtual class which represents a column in a table, and I want the table to be a vector of these generic columns:
template<typename T>
class IColumn {
public:
virtual const std::string& name() = 0;
virtual size_t size() = 0;
virtual T at(size_t idx) = 0;
virtual std::vector<T> data() = 0;
virtual ~IColumn() = default;
};
class StringColumn : public IColumn<std::string> {
public:
StringColumn(std::string name, std::vector<std::string> data)
: name_(std::move(name)), data_(std::move(data)) {}
const std::string& name() override { return name_; }
size_t size() override { return data_.size(); }
const std::vector<std::string>& data() override { return data_; }
std::string at(size_t idx) override { return data_[idx]; }
private:
std::string name_;
std::vector<std::string> data_;
};
class IntColumn : public IColumn<int> {
public:
IntColumn(std::string name, std::vector<int> data)
: name_(std::move(name)), data_(std::move(data)) {}
const std::string& name() override { return name_; }
size_t size() override { return data_.size(); }
const std::vector<int>& data() override { return data_; }
int at(size_t idx) override { return data_[idx]; }
private:
std::string name_;
std::vector<int> data_;
};
However, I am having issues when declaring the vector in the Table class:
class Table {
std::vector<std::unique_ptr<IColumn>> columns;
};
I understand that IColumn is a template class, hence it complains about the missing template parameter, however I am not sure how to get around this issue, because the virtual functions T at() and std::vector<T> data() rely on T.
How could I fix this issue or could someone suggest an alternative design for this API?
EDIT: Using the std::variant<IntColumn, StringColumn> with std::visit as suggested:
for (auto& col: columns_) {
std::cout << std::visit([](auto&& arg) { return arg.name(); }, col) << '\t';
}
std::cout << '\n';
for (int i = 0; i < this->rowCount(); i++) {
for (auto& col : columns_) {
auto v = std::visit([i](auto&& arg) { return arg.at(i); }, col);
std::cout << v;
}
}
The first std::visit works, but the second one doesn't.
Thanks.
| IColumn seems strange, you can indeed go with template:
template <typename T>
class Column {
public:
Column(std::string name, std::vector<T> data) :
m_name(std::move(name)),
m_data(std::move(data))
{}
const std::string& name() const { return m_name; }
std::size_t size() const { return m_data.size(); }
const T& at(size_t idx) const { return m_data.at(idx); }
std::vector<T>& data() { return m_data; }
private:
std::string m_name;
std::vector<T> m_data;
};
and std::variant in Table
struct Table
{
std::vector<std::variant<Column<std::string>, Column<int>>> columns;
};
Usage might be similar to
Table table;
table.columns.push_back(Column<std::string>("string column", {"data1", "data2", "data3"}));
table.columns.push_back(Column<int>("int column", {4, 8, 15}));
const char* sep = "";
for (auto& col: table.columns) {
std::visit([&sep](const auto& arg) { std::cout << sep << arg.name(); }, col);
sep = "\t";
}
std::cout << "\n";
for (std::size_t i = 0; i < table.rowCount(); i++) {
const char* sep = "";
for (const auto& col : table.columns) {
std::visit([i, &sep](const auto& arg) { std::cout << sep << arg.at(i); }, col);
sep = "\t";
}
std::cout << std::endl;
}
Demo
|
70,959,558 | 70,971,954 | boost asio broadcast not going out on all interfaces | If set up a program with boost asio.
Broadcasts are working fine, if only one network interface is present.
However, if there are more network interfaces each broadcast is being sent on one interface only. The interface changes randomly. As observed by wireshark.
I'd expect each broadcast to go out on every interface.
Who's wrong? Me, boost or my understanding of how to use boost. Well, I'm aware, that the latter is the most probable :).
And how can I get the expected behavior.
int myPort=5000;
boost::asio::io_context io_Context{};
boost::asio::ip::udp::socket socket{io_Context};
std::thread sendWorkerThread;
void SendWorkerStart() {
boost::asio::executor_work_guard<decltype(io_Context.get_executor())> work { io_Context.get_executor() };
io_Context.run();
}
void setupSocket() {
socket.set_option(boost::asio::socket_base::reuse_address(true));
socket.set_option(boost::asio::socket_base::broadcast(true));
boost::system::error_code ec;
socket.bind(boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4::any(), myPort), ec);
sendWorkerThread = std::thread(udpSocket_c::SendWorkerStart, this);
SendWorkerStart();
}
void SendBroadcast(UdpMessage_t &&message, int size) {
boost::system::error_code ec;
std::lock_guard<std::mutex> lockGuard(sendMutex);
udp::endpoint senderEndpoint(boost::asio::ip::address_v4::broadcast(), myPort);
socket.async_send_to(boost::asio::buffer(message->data(), size), senderEndpoint,
[this](const boost::system::error_code& error,
std::size_t bytes_transferred) { /* nothing to do */} );
}
Thanks for your help.
Edit: It's now running on Windows, but needs to work also in Linux.
| As suggested by Alan Birtles in the comments to the question i found an explanation here:
UDP-Broadcast on all interfaces
I solved the issue by iterating over he configured interfaces and sending the broadcast to each networks broadcast address as suggested by the linked answer.
|
70,960,205 | 70,961,067 | Syntax error on my member initializer lists | I have the following class:
class MathNode {
protected:
std::list<std::pair<std::string, MathNode*> > myChildren;
public:
MathNode()
: myChildren{} // line 15
{} // line 16
MathNode(std::string l, MathNode* c)
: myChildren{ std::make_pair(l, c) }
{}
MathNode(std::string l1, MathNode* c1,
std::string l2, MathNode* c2)
: myChildren{ std::make_pair(l1, c1),
std::make_pair(l2, c2) }
{}
};
And when I go to compile I get the following errors:
In file included from ./calc.hpp:6:
./nodes.hpp:16:9: error: expected member name or ';' after declaration
specifiers
{}
^
./nodes.hpp:15:25: error: expected '('
: myChildren{}
I tried changing the curlies to parenthesis on line 15, and got these errors:
In file included from ./calc.hpp:6:
./nodes.hpp:19:9: error: expected member name or ';' after declaration
specifiers
{}
^
./nodes.hpp:18:25: error: expected '('
: myChildren{ std::make_pair(l, c) }
^
./nodes.hpp:18:47: error: expected ';' after expression
: myChildren{ std::make_pair(l, c) }
As far as I can tell, I'm using perfectly legal C++11 syntax, and I even explicitly passed the option to use C++11 in my Makefile. What gives?
EDIT: We've narrowed down the issue to a Makefile problem. Here's the Makefile:
all: calc test
calc: parser.o lexer.o calc.o
g++ -std=c++11 -g -o calc calc.o lexer.o parser.o
test: calc
./calc input.txt
%.o: %.cpp
g++ -std=c++11 -g -c $<
lexer.o: lexer.yy.cc
g++ -std=c++11 -g -c $< -o lexer.o
lexer.yy.cc: grammar.hh lexer.l
flex --outfile lexer.yy.cc lexer.l
grammar.hh: parser.yy
bison --defines=grammar.hh -d -v parser.yy
parser.cc: grammar.hh
.PHONY: clean test
clean:
rm -rf *.o *.cc *.hh calc parser.output
EDIT: I solved this in an answer below.
| The solution was to add a rule for parser.o to compile parser.cc:
parser.o: parser.cc
g++ -std=c++11 -g -c $< -o parser.o
|
70,960,372 | 70,960,488 | What is the purpose of back() in c++? | Here is the code:
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> list = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
int total = list[s.back()];
for(int i = s.length() - 2; i>=0; --i){
if(list[s[i]] < list[s[i+1]]){
total -= list[s[i]];
}
else{
total += list[s[i]];
}
}
return total;
}
};
I can't understand what is the purpose of this line:
int total = list[s.back()];
can anyone tell me what is the purpose of
"back()"
in the above code?
| As I have understood the string s contains a number using Roman numerals as for example "IV" that represents 4. So the expression s.back() yields the last symbol in the string that is 'V'.
That is the string is traversed from right to left.
In other words, for sequential containers with rare exceptions the member function front yields the first element of the container and the function back yields the last element of the container.
|
70,960,950 | 70,961,203 | What is time complexity of my sorting algorithm? | It is similar to insertion sort with swap, and for three standards. For example if user inputs 1,2,3 the priority is to sort by height, then weight and then age. I have comparator as well.
The thing is I am not sure about time complexity. Is it going to be O(n^2)? If yes can anyone explain why? Ofc I'm talking about the worst scenario.
struct Person{
string name;
float height; // 1
int weight; // 2
short int age; // 3
};
bool comparePeople(Person a, Person b, short int standardOne, short int standardTwo, short int standardThree )
{
if(standardOne == 1 ){
if( standardTwo == 2){
if (a.height != b.height)
return a.height < b.height;
if (a.weight != b.weight)
return a.weight < b.weight;
return (a.age < b.age);
}
else{ // 1,3,2
if (a.height != b.height)
return a.height < b.height;
if (a.age != b.age)
return a.age < b.age;
return (a.weight < b.weight);
}
}else if(standardOne == 2 ){
if( standardTwo == 1){
if (a.weight != b.weight)
return a.weight < b.weight;
if (a.height != b.height)
return a.height < b.height;
return (a.age < b.age);
}
else{
if (a.weight != b.weight)
return a.weight < b.weight;
if (a.age != b.age)
return a.age < b.age;
return (a.height < b.height);
}
}else if(standardOne == 3 ){
if( standardTwo == 1){
if (a.age != b.age)
return a.age < b.age;
if (a.height != b.height)
return a.height < b.height;
return (a.weight < b.weight);
}
else{ //3,2,1
if (a.age != b.age)
return a.age < b.age;
if (a.weight != b.weight)
return a.weight < b.weight;
return (a.height < b.height);
}
}
}
void sort(Person *GroupOne, short int standardOne, short int standardTwo, short int standardThree, int n){
for(int i = 1; i < n; i++) {
Person key = GroupOne[i];
int j = i - 1;
while (j >= 0 && comparePeople(GroupOne[j],GroupOne[j+1], standardOne, standardTwo, standardThree)) {
Person temp = GroupOne[j+1];
GroupOne[j+1] = GroupOne[j];
GroupOne[j] = temp;
j--;
}
GroupOne[j+1] = key;
}
}
| Yes, it's a quadratic sorting algorithm as you stated in your question. The reasoning is this:
The main part of the code runs a nested loop as follows:
for(int i = 1; i < n; i++) {
int j = i-1
while (j >= 0...
where you do constant work inside the inner loop.
In the worst case, the inner loop iterates i times for each iteration of the outer loop. This create the following famous sequence: 1 + 2 +...+ n-1 + n, which equals n * (n+1)/2. In Big O terms this is O(n^2).
|
70,961,296 | 70,961,928 | Defer/cancel execution of functions and analyze their arguments | I'm trying to write external draw call optimization, and for that I need to collect hooked calls, store their arguments to analyze them later on.
I've been able to make deferred calls, and somewhat readable arguments, stored in tuple, but I need to read arguments from base class and after thorough googling I can't find anything applicable.
I'll work with array of IDelegateBase mostly, and it would be very inconvenient to convert them to Delegate<...> with full signature, when I mostly would read just one argument. Therefore, I need virtual templated method in IDelegateBase, which would return n-th argument. But virtual templated methods are impossible, so probably I'd have to have templated method in base class, which would call non-template (boost::any?) virtual method and cast it's result, I suppose. But, anyway, I can't get n-th element from tuple via runtime variable.
#include <functional>
#include <iostream>
class IDelegateBase
{
public:
virtual void invoke() { }
};
template <typename T, typename... Args>
class Delegate : public IDelegateBase
{
private:
void (*_f)(Args...);
std::tuple<Args...> _args;
public:
Delegate(T& f, Args &...args)
: _f(f), _args(args...) { }
void invoke() final
{
std::apply(_f, _args);
}
};
void a() { std::cout << "a called;\n"; }
void b(int x) { std::cout << "b called with " << x << "\n"; }
void c(int x, float y) { std::cout << "c called with " << x << ", " << y << "\n"; }
int main()
{
IDelegateBase* d = new Delegate(a);
d->invoke();
int i = 42;
d = new Delegate(b, i);
d->invoke();
i = 21;
float f = 0.999;
d = new Delegate(c, i, f);
d->invoke();
// I need something like this:
auto test = d->getArgument<float>(1);
};
Update:
Final solution with kind of type checking: https://godbolt.org/z/xeEWTeosx
| You could provide a virtual function returning void* and use it in a template, but type safety goes down the drain: Should you ever get the type wrong, you'll end up with undefined behaviour.
For getting element using an index you can use a recursive helper template that compares with one index per recursive call.
class IDelegateBase
{
public:
virtual void invoke() { }
template<class T>
T const& getArgument(size_t index) const
{
return *static_cast<T const*>(getArgumentHelper(index));
}
protected:
virtual void const* getArgumentHelper(size_t index) const = 0;
};
template <typename T, typename... Args>
class Delegate : public IDelegateBase
{
private:
void (*_f)(Args...);
std::tuple<Args...> _args;
public:
Delegate(T& f, Args &...args)
: _f(f), _args(args...) { }
void invoke() final
{
std::apply(_f, _args);
}
protected:
void const* getArgumentHelper(size_t index) const override
{
return GetHelper<0>(index, _args);
}
private:
template<size_t index>
static void const* GetHelper(size_t i, std::tuple<Args...> const& args)
{
if constexpr (sizeof...(Args) > index)
{
if (index == i)
{
return &std::get<index>(args);
}
else
{
return GetHelper<index + 1>(i, args);
}
}
else
{
throw std::runtime_error("index out of bounds");
}
}
};
The use of if constexpr is needed here, since std::get does not compile if a of tuple index out of bounds is used.
|
70,961,375 | 70,961,575 | C++ vs. python: daylight saving time not recognized when extracting Unix time? | I'm attempting to calculate the Unix time of a given date and time represented by two integers, e.g.
testdate1 = 20060711 (July 11th, 2006)
testdate2 = 4 (00:00:04, 4 seconds after midnight)
in a timezone other than my local timezone. To calculate the Unix time, I feed testdate1, testdate2 into a function I adapted from Convert date to unix time stamp in c++
int unixtime (int testdate1, int testdate2) {
time_t rawtime;
struct tm * timeinfo;
//time1, ..., time6 are external functions that extract the
//year, month, day, hour, minute, seconds digits from testdate1, testdate2
int year=time1(testdate1);
int month=time2(testdate1);
int day=time3(testdate1);
int hour=time4(testdate2);
int minute=time5(testdate2);
int second=time6(testdate2);
time ( &rawtime );
timeinfo = localtime ( &rawtime );
timeinfo->tm_year = year - 1900;
timeinfo->tm_mon = month - 1;
timeinfo->tm_mday = day;
timeinfo->tm_hour = hour;
timeinfo->tm_min = minute;
timeinfo->tm_sec = second;
int date;
date = mktime(timeinfo);
return date;
}
Which I call from the main code
using namespace std;
int main(int argc, char* argv[])
{
int testdate1 = 20060711;
int testdate2 = 4;
//switch to CET time zone
setenv("TZ","Europe/Berlin", 1);
tzset();
cout << testdate1 << "\t" << testdate2 << "\t" << unixtime(testdate1,testdate2) << "\n";
return 0;
}
With the given example, I get unixtime(testdate1,testdate2) = 1152572404, which according to
https://www.epochconverter.com/timezones?q=1152572404&tz=Europe%2FBerlin
is 1:00:04 am CEST, but I want this to be 0:00:04 CEST.
The code seems to work perfectly well if I choose a testdate1, testdate2 in which daylight saving time (DST) isn't being observed. For example, simply setting the month to February with all else unchanged is accomplished by setting testdate1 = 20060211. This gives
unixtime(testdate1,testdate2) = 1139612404, corresponding to hh:mm:ss = 00:00:04 in CET, as desired.
My impression is that setenv("TZ","Europe/Berlin", 1) is supposed to account for DST when applicable, but perhaps I am mistaken. Can TZ interpret testdate1, testdate2 in such a way that it accounts for DST?
Interestingly, I have a python code that performs the same task by changing the local time via os.environ['TZ'] = 'Europe/Berlin'. Here I have no issues, as it seems to calculate the correct Unix time regardless of DST/non-DST.
| localtime sets timeinfo->tm_isdst to that of the current time - not of the date you parse.
Don't call localtime. Set timeinfo->tm_isdst to -1:
The value specified in the tm_isdst field informs mktime() whether or not daylight saving time (DST) is in effect for the time supplied in the tm structure: a positive value means DST is in effect; zero means that DST is not in effect; and a negative value means that mktime() should (use timezone information and system databases to) attempt to determine whether DST is in effect at the specified time.
See the code example in https://en.cppreference.com/w/cpp/chrono/c/mktime
|
70,961,570 | 70,962,012 | Delete in Linked List | So I revisited double linked list, found I'm really stupid, and can't figure things out even when I narrowed down problem to delete operator. I'm still playing around with templates, so maybe there's something wrong with templates as well. Print works fine without deleting a node. Please tell me what's wrong.
Result of code run is just that it doesn't print anything.
template<typename T>
class DoubleLinkedList
{
struct Node;
Node *head;
Node *tail;
public:
DoubleLinkedList(Node *head = nullptr) : head(head) {
if (head == nullptr) {
tail = nullptr;
return;
}
Node *tmp;
for (tmp = head; tmp->next != nullptr; tmp = tmp->next);
tail = tmp;
}
void addfront(T val) {
Node *newnode = new Node(val, head);
if (head == nullptr) {
head = tail = newnode;
return;
}
newnode->next = head;
head->prev = newnode;
head = newnode;
}
void addend(T val) {
Node *newnode = new Node(val, nullptr, tail);
// There's probably a very obvious reason here, but my brain is busted and can't figure out
// what's wrong
if (head == nullptr) {
head = tail = newnode;
return;
}
tail->next = newnode;
newnode->prev = tail;
tail = newnode;
}
void del(T val) {
for (Node *tmp = head; tmp != nullptr; tmp = tmp->next) {
if (tmp->value == val) {
if (tmp != head)
tmp->prev->next = tmp->next;
else
head = tmp->next;
if (tmp->next != nullptr)
tmp->next->prev = tmp->prev;
else
tail = tmp->prev;
// print();
delete tmp; // delete not working, even when delete function is empty with just
// delete head, it's a memory issue that my head can't wrap around
break;
}
}
}
void print()
{
for (Node *tmp = head; tmp != nullptr; tmp = tmp->next)
std::cout << tmp->value << ", ";
}
~DoubleLinkedList() {
Node *tmp;
for (tmp = head; tmp->next != nullptr; tmp = tmp->next)
delete tmp->prev;
delete tmp->prev;
delete tmp;
}
};
template<typename T>
struct DoubleLinkedList<T>::Node : DoubleLinkedList<T>
{
T value;
Node *prev;
Node *next;
Node(T val, Node *next = nullptr, Node *prev = nullptr) :
value(val), prev(prev), next(next) {}
};
int main()
{
DoubleLinkedList<int> numlist;
for (int i = 0; i < 10; i++)
numlist.addend(i);
numlist.del(0);
numlist.print();
}
| The ~DoubleLinkedList() logic is all wrong. When the list is empty, head is nullptr, so accessing tmp->next in the loop is undefined behavior. And the way you are deleting nodes is just weird in general. It should look more like this instead:
~DoubleLinkedList() {
Node *tmp, *next;
for (tmp = head; tmp != nullptr; tmp = next) {
next = tmp->next;
delete tmp;
}
}
The reason this was causing problems is because you have DoubleLinkedList::Node deriving from DoubleLinkedList, so delete'ing a node was calling the invalid ~DoubleLinkedList() destructor. There is no good reason for Node to derive from DoubleLinkedList at all.
After fixing those 2 things, the rest of the code works fine for me, especially the del() call:
#include <iostream>
using namespace std;
template<typename T>
class DoubleLinkedList
{
struct Node
{
T value;
Node *prev;
Node *next;
Node(T val, Node *next = nullptr, Node *prev = nullptr) :
value(val), prev(prev), next(next) {}
};
Node *head;
Node *tail;
public:
DoubleLinkedList(Node *head = nullptr) : head(head) {
if (head == nullptr) {
tail = nullptr;
return;
}
Node *tmp;
for (tmp = head; tmp->next != nullptr; tmp = tmp->next);
tail = tmp;
}
void addfront(T val) {
Node *newnode = new Node(val, head);
if (head == nullptr) {
head = tail = newnode;
return;
}
newnode->next = head;
head->prev = newnode;
head = newnode;
}
void addend(T val) {
Node *newnode = new Node(val, nullptr, tail);
if (head == nullptr) {
head = tail = newnode;
return;
}
tail->next = newnode;
newnode->prev = tail;
tail = newnode;
}
void del(T val) {
for (Node *tmp = head; tmp != nullptr; tmp = tmp->next) {
if (tmp->value == val) {
if (tmp != head)
tmp->prev->next = tmp->next;
else
head = tmp->next;
if (tmp->next != nullptr)
tmp->next->prev = tmp->prev;
else
tail = tmp->prev;
// print();
delete tmp;
break;
}
}
}
void print()
{
for (Node *tmp = head; tmp != nullptr; tmp = tmp->next)
std::cout << tmp->value << ", ";
std::cout << "\n";
}
~DoubleLinkedList() {
Node *tmp, *next;
for (tmp = head; tmp != nullptr; tmp = next) {
next = tmp->next;
delete tmp;
}
}
};
int main()
{
DoubleLinkedList<int> numlist;
for (int i = 0; i < 10; i++)
numlist.addend(i);
numlist.print();
numlist.del(0);
numlist.print();
}
Online Demo
|
70,961,923 | 70,962,185 | Is casting strings from `wchar_t` to `char16_t` legal if encoding and width is the same? | On Windows, wchar_t is a UTF-16(LE) formatted character, which is -- for the most part -- equivalent to char16_t. However, these two character types are still distinct types in the C++ type-system -- which makes me uncertain whether converting between sequences of these two character types is legal as per the C++ standard.
My question is this: In C++17, is it legal to perform the following casts, and to read from the converted pointers:
reinterpret_cast<const wchar_t*>(char16_ptr) where decltype(char16_ptr) is const char16_t*, and
reinterpret_cast<const char16_t*>(wchar_ptr) where decltype(wchar_ptr) is const wchar_t*
For the purposes of this question, assume the following:
sizeof(wchar_t) == sizeof(char16_t), and
wchar_t is formatted the same as char16_t (as is the case on Windows)
Basically, is this a violation of a strict-aliasing?
My understanding that the cast itself is valid thanks to [expr.reinterpret.cast]/7, but that the result of the cast cannot safely be used since the type is being aliased by something that isn't char, unsigned char, or std::byte. Is this interpretation correct?
Note: Other questions have been asked regarding wchar_t and char16_t being the same, but this question is not a duplicate of those as far as I can tell. Notably, the question "Are wchar_t and char16_t the same on Windows?" actually performs a reinterpret_cast between pointers, but none of the answers actually address whether this cast was ever legal in the first place.
| You already know the answer to this: strictly speaking, no.
wchar_t is not char16_t. Neither derives from the other. Neither is similar to the other. Neither is a signed/unsigned version of the other. Neither is an aggregate containing the other.And neither of them is a bytewise type (char, etc).
So you cannot access a wchar_t through a pointer/reference to a char16_t.
If strict avoidance of strict aliasing is your goal, you're going to have to copy the data to a different object. That is valid, assuming they both have the same representation.
|
70,962,146 | 70,970,712 | Can't understand the requirement from the exercise | this https://projecteuler.net/problem=641 is the problem I am trying to solve and below is my half solution.
void dice(int n)
{
int i, j, dices[n];
for(i = 0; i < n; i++) {
dices[i] = 1;
}
for(i = 1; i < n; i++)
{
for(j = 0; j < n; j+=i)
{
dices[j]= dices[j] > 5?1:dices[j]+1;
}
};
for(i = 0; i < n; i++) {
cout << i+1 << "th dice is :" << dices[i] << endl;
}
};
this is the part I do not get: Let f(n) be the number of dice that are showing a 1 when the process finishes. You are given f(100)=2 and f(10^8)=69. Find f(10^36).
from "f(100)=2" I understand that the 100th die should be 2 but f(10^8)=69 loses me.
| Read the problem description again. There is a definition of f() there:
Let f(n) be the number of dice that are showing a 1 when the process finishes.
It is not a value of any specific die. Instead, the value of f(n) tells you how many dice in the n–dice row show 1 after completion of all turns.
|
70,962,623 | 70,962,788 | Convert Pixels Buffer type from 1555 to 5551 (C++, OpenGL ES) | I'm having a problem while converting OpenGL video plugin to support GLES 3.0
So far everything went well, except glTexSubImage2D the original code uses GL_UNSIGNED_SHORT_1_5_5_5_REV as pixels type which is not supported in GLES 3.0
the type that worked is GL_UNSIGNED_SHORT_5_5_5_1 but colors and pixels are broken,
so I thought converting the pixels buffer would be fine..
but due to my limited understanding in GL and C++ I didn't succeed to do that.
Pixels process:
the pixels will be converted internally to 16 bit ABGR as in the Shader comments:
// Take a normalized color and convert it into a 16bit 1555 ABGR
// integer in the format used internally by the Playstation GPU.
uint rebuild_psx_color(vec4 color) {
uint a = uint(floor(color.a + 0.5));
uint r = uint(floor(color.r * 31. + 0.5));
uint g = uint(floor(color.g * 31. + 0.5));
uint b = uint(floor(color.b * 31. + 0.5));
return (a << 15) | (b << 10) | (g << 5) | r;
}
it will be received by this method after processing by vGPU:
static void Texture_set_sub_image_window(struct Texture *tex, uint16_t top_left[2], uint16_t resolution[2], size_t row_len, uint16_t* data)
{
uint16_t x = top_left[0];
uint16_t y = top_left[1];
/* TODO - Am I indexing data out of bounds? */
size_t index = ((size_t) y) * row_len + ((size_t) x);
uint16_t* sub_data = &( data[index] );
glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint) row_len);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, tex->id);
glTexSubImage2D(GL_TEXTURE_2D, 0,
(GLint) top_left[0], (GLint) top_left[1],
(GLsizei) resolution[0], (GLsizei) resolution[1],
GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV /* Not supported in GLES */,
(void*)sub_data);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
}
as for row_len it's get the value from #define VRAM_WIDTH_PIXELS 1024
What I tried to do:
1st I replaced the type with another one:
glTexSubImage2D(GL_TEXTURE_2D, 0,
(GLint) top_left[0], (GLint) top_left[1],
(GLsizei) resolution[0], (GLsizei) resolution[1],
GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1 /* <- Here new type */,
(void*)sub_data);
2nd converted sub_data using this method:
uint16_t* ABGRConversion(const uint16_t* pixels, int row_len, int x, int y, int width, int height) {
uint16_t *frameBuffer = (uint16_t*)malloc(width * row_len * height);
signed i, j;
for (j=0; j < height; j++)
{
for (i=0; i < width; i++)
{
int offset = j * row_len + i;
uint16_t pixel = pixels[offset];
frameBuffer[offset] = Convert1555To5551(pixel); //<- stuck here
}
}
return frameBuffer;
}
I have no idea what Convert1555To5551 should look like?
Note: Sorry if some descriptions is wrong, I don't really have full understanding for the whole process.
Performance is not major problem.. just need to know how to deal with the current pixel buffer.
Side note: I had to replace glFramebufferTexture with glFramebufferTexture2D so I hope it's not involved in the issue.
Thanks.
| This should be what you're looking for.
uint16_t Convert1555To5551(uint16_t pixel)
{
// extract rgba from 1555 (1 bit alpha, 5 bits blue, 5 bits green, 5 bits red)
uint16_t a = pixel >> 15;
uint16_t b = (pixel >> 10) & 0x1f; // mask lowest five bits
uint16_t g = (pixel >> 5) & 0x1f;
uint16_t r = pixel & 0x1f;
// compress rgba into 5551 (5 bits red, 5 bits green, 5 bits blue, 1 bit alpha)
return (r << 11) | (g << 6) | (b << 1) | a;
}
|
70,962,870 | 70,963,445 | Build Qt project with same filenames in different directories | In a typical C++ application (no Qt), I may have the following:
app/include/namespace1/Foo.h
app/src/namespace1/Foo.cpp
app/include/namespace2/Foo.h
app/src/namespace2/Foo.cpp
Where "app" is the root folder for the project. The classes in those files are:
//In app/include/namespace1/Foo.h
namespace namespace1 {
class Foo;
}
//In app/include/namespace2/Foo.h
namespace namespace2 {
class Foo;
}
In a build system like the one eclipse has, the object files for each .cpp files will be built into diffrent subdirectories.
In Qt, I create a .pri file in each of my folders which contains include, SOURCES, and HEADERS statements. However, when Qt builds the program, it places all of the object files in the same directory. So, [build output]/Foo.o gets generated twice and thus overwritten causing the linker to fail.
I looked into making each nested folder into its own SUBDIRS project with its own .pro file, but this doesn't work correctly since each folder is not an independent project, just an independent namespace.
What is the correct way to setup a project like this?
| Here is one answer: https://riptutorial.com/qt/example/15975/preserving-source-directory-structure-in-a-build--undocumented---object-parallel-to-source--option--
This causes Qt to generate a directory structure in the build directory that "mirrors" the source directories.
|
70,963,295 | 70,964,104 | Turn C string literal into std::integer_sequence at compile-time with C++17 | Is it possible to write a construct that turns any C string literal "XY..." into a type std::integer_sequence<char, 'X', 'Y', ...> at compile time? I really want a character pack, not a std::array.
Something like
using MyStringType = magic_const_expr("MyString");
A nice approach using the literal operator was demonstrated here but unfortunately it requires a non-standard compiler extension.
| Something like this might do it:
template <size_t N, typename F, size_t... indexes>
constexpr auto make_seq_helper(F f, std::index_sequence<indexes...> is) {
return std::integer_sequence<char, (f()[indexes])...>{};
}
template <typename F>
constexpr auto make_seq(F f) {
constexpr size_t N = f().size();
using indexes = std::make_index_sequence<N>;
return make_seq_helper<N>(f, indexes{});
};
template<const char* str>
struct IntegerSequenceFromString {
private:
constexpr static auto value = make_seq([](){return std::string_view{str}; });
public:
using type = decltype(value);
};
Usage would then be:
constexpr static const char str[] = "lala";
IntegerSequenceFromString<str>::type i{};
Here is a live example of it working.
I am sure, there is a way to reduce some of this extra stuff as well, but from the assembly, it looks like we don't generate any real runtime variables: https://godbolt.org/z/f65cjGfzn
|
70,963,319 | 70,967,279 | Cannot read back serialized data using protocol buffer in C++ platform | I have just started to use protocol buffer and try to make a minimal example to write and read back data. But I am failed to read back the serialized data.
Sources I have used to make the example
1, 2, 3.
My Approach
Structure and Code to generate serialized data
.
├── CMakeLists.txt
├── lib
│ └── libproto_library.so # creted after the compilation
├── proto
│ └── message.proto
├── README.md
├── run_project.sh
└── src
└── main.cpp
Points to be noted
I have compiled the project using cmake. Ignored the cmake file not to make the post messy. If needed, I can provide.
build folder is not shown in the structure. Generated header files by protoc complers are resided there.
message.proto
syntax = "proto3";
package message;
message Sensor {
int32 humidity = 1;
}
main.cpp
#include <fstream>
#include <iostream>
#include "message.pb.h"
using namespace std;
int main(int argc, char const *argv[])
{
message::Sensor sensor;
sensor.set_humidity(68);
std::fstream ofs("../bin/message.data", std::ios_base::out | std::ios_base::binary);
sensor.SerializeToOstream(&ofs);
return 0;
}
After building the project, I have used the generated message.pb.h, message.data and libproto_library.so.
Structure and code to deserialize data
.
├── CMakeLists.txt
├── include
│ └── message.pb.h
├── lib
│ └── libproto_library.so
├── read_back_proto.sh
└── src
├── main.cpp
└── message.data
main.cpp
#include <fstream>
#include <iostream>
#include <string>
#include "message.pb.h"
int main()
{
std::fstream ifs ("message.data", std::ios_base::out | std::ios_base::binary);
message::Sensor sensor;
sensor.ParseFromIstream(&ifs);
int32_t read_humidity = sensor.humidity();
std::cout << "humidity : " << read_humidity << std::endl;
return 0;
}
After compiling this project, the generated executable file provides me the value of humidity is ZERO while I expect it would be 68.
Looking for the suggestion to get back the correct value.
| Encircled in a minor issue really. The path of message.data was wrong.
Firstly, I was opening file with std::ios_base::out. Syntactical error. Already edited in the question though.
Executable file is executing from bin directory
message.data is located in 1 level up of bin, in the src directory
Corrected code to read back serialized data:
#include <fstream>
#include <iostream>
#include <string>
#include "message.pb.h"
int main()
{
std::fstream ifs ("../src/message.data", std::ios_base::in | std::ios_base::binary);
message::Sensor sensor;
sensor.ParseFromIstream(&ifs);
int32_t read_humidity = sensor.humidity();
std::cout << "humidity : " << read_humidity << std::endl;
return 0;
}
|
70,963,558 | 70,963,886 | How to use matcher in google test (error: undeclared identifier) | I'm trying to use google test to test a C function. A simple test using ASSERT_NO_FATAL_FAILURE(); and also EXPECT_THAT();. But when I try to use matchers (like not null for example) the IDE says: Use of undeclared identifier 'NotNull'.
#include "gtest/gtest.h"
extern "C" {
#include "first_tdd.h"
}
TEST(sum, sum_has_return)
{
EXPECT_THAT(sum(), NotNull());
}
cmake_minimum_required(VERSION 3.19)
project(untitled C)
set(CMAKE_C_STANDARD 99)
add_executable(main.c sum.c)
# 'Google_test' is the subproject name
project(Google_tests)
# 'lib' is the folder with Google Test sources
add_subdirectory(googletest)
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR}, ${gmock_SOURCE_DIR}/include ${gmock_SOURCE_DIR})
# 'Google_Tests_run' is the target name
# 'test1.cpp tests2.cpp' are source files with tests
set(Sources
sum.c
)
add_executable(Google_Tests_run sum_tests.cpp sum.c)
target_link_libraries(Google_Tests_run gtest gtest_main)
Message when I try to run the test.
error: use of undeclared identifier 'NotNull'
EXPECT_THAT(sum(), NotNull());
^
1 error generated.
make[3]: *** [CMakeFiles/Google_Tests_run.dir/sum_tests.cpp.o] Error 1
make[2]: *** [CMakeFiles/Google_Tests_run.dir/all] Error 2
make[1]: *** [CMakeFiles/Google_Tests_run.dir/rule] Error 2
make: *** [Google_Tests_run] Error 2
Folder Structure
Does any one know if I should include something else?
Thank you.
| NotNull is declared in the namespace ::testing. Possible fixes
TEST(sum, sum_has_return)
{
EXPECT_THAT(sum(), ::testing::NotNull());
}
or
TEST(sum, sum_has_return)
{
using ::testing::NotNull;
EXPECT_THAT(sum(), NotNull());
}
|
70,965,055 | 70,965,429 | Raw pointer but modern way | I have to have a semantic stack in my project which is going to hold multiple types in it.
I aim to have my project to use modern C++.
What is the correct way to have a stack of any type ?
Equivalent version in java is Stack<Object>.
Which of these are correct?
Use void* and cast it to the type I want.
Something as 1 but using some smart pointers. (I don't know what)
|
std::any is for storing objects of any type (limitations may apply).
However, the entire design of storing any type is rarely ideal. Often, it's better to use variadic templates to keep polymorphism entirely compile time, or to have only a limited set of types (std::variant), or even to use an OOP hierarchy. Which is more appropriate depends on the use case.
|
70,965,523 | 70,968,869 | simulate selection in windows C++ | I have this in my Notepad:
hello
I want to simulate selecting in C++ using Windows' keybd_event function.
here is my code:
keybd_event(VK_SHIFT, 0, 0, 0);
for (size_t i = 0; i < 5; i++)
{
keybd_event(VK_LEFT, 0, 0, 0);
keybd_event(VK_LEFT, 0, KEYEVENTF_KEYUP, 0);
}
keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);
but after I run this, it didn't select anything, it just go to the start of the file. Why isn't this working?
| Add KEYEVENTF_EXTENDEDKEY will select rightly.
https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-keybdinput#members
#include <windows.h>
void main()
{
Sleep(2000);
keybd_event(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0), KEYEVENTF_EXTENDEDKEY, 0);
for (size_t i = 0; i < 5; i++)
{
keybd_event(VK_LEFT, 0, 0, 0);
keybd_event(VK_LEFT, 0, KEYEVENTF_KEYUP, 0);
Sleep(20);
}
keybd_event(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
Use VK_SHIFT in keybd_event, There is a problem that shift cannot be released,I recommend you use SendInput instead of keybd_event.
For higher-level operations, I also recommend you use UI Automation.
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput
https://learn.microsoft.com/en-us/windows/win32/winauto/entry-uiauto-win32
|
70,965,785 | 70,966,048 | Rounding errors in lethal dose calculator program | I was given an assignment that asks me to find the lethal dose of soda in grams for an inputted weight from the user. I am having many issues with rounding errors... this should be simple and not sure why I'm having so many issues with it. For example, here are a couple of inputs and outputs that are causing problems. Thanks in advance!
Input of 1 1000 275: expected [124850000, 356714286] but found [1.2485e+08, 3.56714e+08]
Input of 60 390 130: expected [383630, 1096086] but found [383630, 1.09609e+06]
/**
* @author
* @date 2-2-22
* @file h02.cpp
*/
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
/**
* Finds lethal dose (in grams) of artificial sweetener for a given dieter weight.
* Also finds the number of cans of soda that would be lethal for a given weight.
* @return 0 for success.
*/
int run()
{
// Add your implementation comments here
// Write your code here
const double dose_per_can {.001}; // percentage of lethal sweetener in one can
const int soda_weight {350}; //in grams
const int pound_to_grams {454}; //in grams
double dieter_weight {};
double mouse_weight {};
double mouse_lethal {};
double dieter_lethal {}; // lethal dose in grams to human/dieter
double lethal_ratio {};
float lethal_per_can {}; //how many grams of art sweetener in a can
double dieter_lethal_cans {};
cout << "Enter mouse weight, lethal dose for mouse (grams), and desired wight of dieter (pounds): " << endl;
cin >> mouse_weight >> mouse_lethal >> dieter_weight;
lethal_ratio = mouse_lethal / mouse_weight; //finding the ratio between the dose given and the weight of the mouse
//lets us use this weight ratio on humans
dieter_lethal = lethal_ratio * (dieter_weight * pound_to_grams); //grams of sweetener that is lethal to dieter with given weight
lethal_per_can = soda_weight * dose_per_can; //find how many grams of sweetener in 1 can.. ends up being constant of .35
dieter_lethal_cans = dieter_lethal / lethal_per_can; // finds how many cans would be lethal to dieter
cout << "Lethal dose in grams, cans is [" << dieter_lethal << ", " <<round(dieter_lethal_cans) << "]" << endl;
return 0;
}
| The round you use returns a floating point value. You need lround - see here: https://en.cppreference.com/w/cpp/numeric/math/round
cout << "Lethal dose in grams, cans is [" << lround(dieter_lethal) << ", "
<< lround(dieter_lethal_cans) << "]" << endl;
Lethal dose in grams, cans is [124850000, 356714292]
|
70,966,204 | 70,966,487 | C++ call to list constructor is ambiguous | I'm trying to build an old C++ project on a modern version of Clang and getting lots of ambiguous errors. I don't have much C++ experience so apologies if this is basic stuff.
/home/ubuntu/NameAndTypeResolver.cpp:124:40: error: call to constructor of 'list<list<const dev::libcrunch::ContractDefinition *> >' is ambiguous
list<list<ContractDefinition const*>> input(1, {});
^ ~~~~~
I'm not sure what the compilers asking for here. Additionally what is the {} syntax?
| To solve your problem do this:
std::list<std::list<ContractDefinition const*>> input(1);
// ^^^^ drop the ,{}
The {} is an attempt to constructor an object of type std::list<ContractDefinition const*> (i.e. a single member of the input).
In C++ 11 the original line would have been valid as it was unambiguously making a single object of std::list<ContractDefinition const*> using the default constructor.
But in C++ 17 (and later, not sure if it applies to C++14) the {} can be used for the default constructor and to create an initializer list (std::initializer_list).
The std::list<X> has a constructor that takes (<Count>, <Object>). When the compiler sees '{}it can default construct anXusingX{}or create anstd::initializer_list` (or length zero) both are valid options in this context. The compiler is not allowed to make that kind of determination which to use (even though they both result in the same thing in this case).
I hope I got that correct.
I'll check for negative marks in the morning :-)
|
70,966,753 | 70,967,309 | C++ reading from file is not giving expected, or any output | I am trying to make a game which loads it's levels from a text file. I decided to do this with the help of a 2 dimensional vector of integers. Before implementing it in my main code, I first decided to check whether my logic was right so I made a Test.txt file containing the the level I wanted to draw.
Test.txt:-
1 1 0 0 1 0 0 0 0 0 1 1 1 1 1 1 1 0 1 0 1 0 0 1 0 0 1 0 0 1 1 0
1 0 1 0 1 1 1 0 1 1 0 1 1 0 1 1 1 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0
0 0 0 0 0 0 0 1 0 1 0 0 0 1 1 0 1 1 0 0 0 0 0 0 1 0 0 1 0 1 1 0
0 0 1 1 1 1 1 0 0 0 1 0 1 0 1 1 0 0 0 1 1 1 1 0 0 0 1 0 1 1 1 0
1 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 1 0 1
0 1 0 1 0 1 1 1 0 0 1 0 0 0 0 1 0 1 0 0 1 0 1 1 0 0 0 0 1 1 0 1
0 1 1 1 0 1 1 0 1 0 1 1 0 1 1 0 0 1 0 0 0 1 1 0 1 1 1 1 1 1 0 1
0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 1 0 1 0 1 1 0 0 1 0 0 0 1 0 0
0 0 1 1 1 0 0 0 1 0 0 1 1 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 1 0 1
0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 1 0 1 1 0 1 0 0 1 1 1 1 0 1 1
1 1 0 1 1 1 1 0 0 1 0 0 1 0 0 1 0 1 0 1 1 1 1 1 0 0 0 1 1 0 1 0
0 0 1 0 0 0 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 1 0 1 0 0 0 0 1 1 0 1
0 1 1 0 0 0 0 0 0 1 1 0 1 1 0 1 1 0 1 0 0 1 0 0 1 1 0 1 1 1 1 0
1 0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 0 0 1 1 0 0 0
1 0 1 1 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0 1 0 0 0 1 0 1 0 1 1 0 0 1
0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0
0 0 0 1 0 1 0 1 0 1 0 0 1 1 1 0 0 1 1 0 1 0 1 0 1 1 1 0 0 0 1 0
1 0 1 0 1 0 0 0 1 1 0 0 0 1 0 1 1 1 1 1 0 0 1 0 1 0 1 1 1 1 1 1
Each integer is seperated by a space and only one number is supposed to be read once at a time. The 1 and 0 tell the game which tile to draw. Now, with this wrote the following code in c++ to read the file and populate the vector with it's contents. After that it's supposed to output the contents of the vector.
Test.cpp:-
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int num;
vector<vector<int>> nums;
int main(void) {
ifstream FileIn;
FileIn.open("Test.txt");
for(int i = 0; i < 18; i++) {
vector<int> temp;
for(int j = 0; j < 32; j++) {
FileIn >> num;
temp.push_back(num);
}
nums.push_back(temp);
temp.clear();
}
cout << nums.size() << '\n'; // outputs 18
for (unsigned int i=0; i < nums.size(); i++) {
for (unsigned int j=0; j < nums[i].size(); j++) {
cout << nums[i][j];
if (j == nums[i].size() - 1) cout << '\n';
}
}
FileIn.close();
return 0;
}
but this is where the problem starts. The code doesn't output anything to the terminal it just starts and then goes back to the prompt.
The executable compiles with no errors and there are no crashes or runtime error either. There is just no output.
Things i have tried:
Putting in spaces between the numbers
Keeping all integers on the same line
both of the solutions above, but together this time
I am using atom with the platformio terminal plugin on windows 10 (64-bit) on a intel with amd-64 architecture. Any help would be very appreciated.
| So I finally found the problem, the code, logic, text file everything were working fine. After taking the advice about debuggers from the other answer, this time instead of using atom's terminal plugin, I used powershell and it worked. It gave the output i was expecting. Then i tried the same code with the atom's terminal and that gave no output. So the problem seemed to be not in the code but in the terminal I was using.
|
70,966,768 | 70,967,321 | How to parse below JSON with nested array in C++ and retrieve the result | I have a JSON like below which need to be parsed in C++ using read_json.
[
{
"key": "123",
"revoked": false,
"metadata": [
{
"visible": true,
"key": "abc",
"value": "0"
},
{
"visible": true,
"key": "cdf",
"value": "0"
}
],
"meterAttributes": []
}
]
In the above JSON, metadata and its key/value to be retrieved.
boost::property_tree::read_json(jsonString, pt);
for (auto& outerArray : pt)
{
for (auto& arrayProperty : outerArray.second)
{
if (arrayProperty.first == ws2s(metadata))
{
The above code doesn't brought up the result as expected.
| I'd suggest Boost JSON:
#include <boost/json.hpp>
#include <fmt/ranges.h>
#include <iostream>
namespace json = boost::json;
int main() {
std::map<std::string, std::string> kv;
auto doc = json::parse(sample);
for (auto& toplevel : doc.as_array()) {
for (auto& md : toplevel.at("metadata").as_array()) {
kv.emplace(md.at("key").as_string(), md.at("value").as_string());
}
}
fmt::print("Parsed: {}\n", kv);
}
Printing: Live On Compiler Explorer
Parsed: {("abc", "0"), ("cdf", "0")}
Alternative
If you insist on using Boost PropertyTree (e.g. because your data represents a property tree): Live On Compiler Explorer
#include <boost/property_tree/json_parser.hpp>
#include <fmt/ranges.h>
#include <map>
int main() {
std::map<std::string, std::string> kv;
boost::property_tree::ptree doc;
std::istringstream is(sample);
read_json(is, doc);
for (auto& [_, toplevel] : doc) {
for (auto& [_, md] : toplevel.get_child("metadata")) {
kv.emplace(md.get("key", ""), md.get("value", ""));
}
}
fmt::print("Parsed: {}\n", kv);
}
Printing the same.
|
70,967,008 | 70,967,151 | whats wrong with this code it just give Enter an Alphabet= j ERROR! (Enter one Alphabet only not two Alphabet or a number) | #include <stdio.h>
int main(void)
{
char a;
printf("Enter an Alphabet=\n");
scanf("%c",&a);
if(a>=0)
{
printf("ERROR!\n(Enter one Alphabet only not two Alphabet or a number)");
}
else
{
switch (a)
{
case 'a' :
printf("It is vowel");
break;
case 'e' :
printf("It is vowel");
break;
case 'i' :
printf("It is vowel");
break;
case 'o' :
printf("It is vowel");
break;
case 'u' :
printf("It is vowel");
break;
default :
printf("it is a constant");
}
}
return 0;
}
this code just give this result
Enter an Alphabet=
r
ERROR!
(Enter one Alphabet only not two Alphabet or a number)
--------------------------------
Process exited after 2.259 seconds with return value 0
Press any key to continue . . .
| To check if a character is an alphabetical character, you should use the isalpha function.
Putting together my other pointer (checking what scanf returns as well as using tolower, the code could be written something like this:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char a;
printf("Enter an alphabetical character: ");
if (scanf(" %c", &a) != 1)
{
printf("Error reading input\n");
return 1;
}
if (!isalpha(a))
{
printf("Character is not an alphabetical character\n");
return 1;
}
switch (tolower(a))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("It's a vowel\n");
break;
default:
printf("It's a consonant\n");
break;
}
}
[Note that the above code is still written in plain C, not C++]
|
70,967,139 | 70,967,386 | I am not getting how the structure is being passed to a function in following code using call by reference? | Like in this code, what I don't understand is how 'n1' [ increment(n1) ] is being passed to 'number& n2'[void increment(number& n2)].
how can we pass n1 into &n2?
Please let me know if I am getting the basics wrong, because its only recently that i have started to learn C and C++.
// C++ program to pass structure as an argument
// to the functions using Call By Reference Method
#include <bits/stdc++.h>
using namespace std;
struct number {
int n;
};
// Accepts structure as an argument
// using call by reference method
void increment(number& n2)
{
n2.n++;
}
void initializeFunction()
{
number n1;
// assigning value to n
n1.n = 10;
cout << " number before calling "
<< "increment function:"
<< n1.n << endl;
// calling increment function
increment(n1);
cout << "number after calling"
<< " increment function:" << n1.n;
}
// Driver code
int main()
{
// Calling function to do required task
initializeFunction();
return 0;
| Since you are taking the parameter to increment function as a refrence so when you pass n1 to it as follows:
increment(n1);
It is passed as a reference to the increment function which basically means that alias of n1 is created with the name n2
void increment(number& n2)
This means whenever there is a change in n2, It is also reflected in n1(Because they are refering to the same location)
Also, passing a variable as Reference means allowing a function to modify a variable without creating a copy of it by declaring reference variables. The memory location of the passed variable and parameter is the same and therefore, any change to the parameter reflects in the variable itself.
So, after the function call:
n1.n is incremented
|
70,967,271 | 70,971,423 | Overload resolution between constructors from initalizer_list and from a value requiring conversion, compilers diverge | In the following code, struct A has two constructors: A(int) and A(std::initializer_list<char>). Then an object of the struct is created with A({0}):
#include <initializer_list>
struct A {
int a;
constexpr A(int) { a = 1; }
constexpr A(std::initializer_list<char>) { a = 2; }
};
static_assert( A({0}).a == 2 );
It turns out that GCC and Clang prefer here the constructor from initializer_list (despite int argument has to be converted in char) and the whole program is accepted, but MSVC selects A(int) constructor, failing the static_assert. Demo: https://gcc.godbolt.org/z/qx7W417Mv
Which compiler is right here?
| Clang & GCC are right, MSVC has a bug
This is CWG 1589:
1589. Ambiguous ranking of list-initialization sequences
Section: 16.3.3.2 [over.ics.rank]
Status: CD4
Submitter: Johannes Schaub
Date: 2012-11-21
[Moved to DR at the November, 2014 meeting.]
The interpretation of the following example is unclear in the current
wording:
void f(long);
void f(initializer_list<int>);
int main() { f({1L});
The problem is that a list-initialization sequence can also be a
standard conversion sequence, depending on the types of the elements
and the type of the parameter, so more than one bullet in the list
in 16.3.3.2 [over.ics.rank] paragraph 3 applies:
[...]
These bullets give opposite results for the example above, and there
is implementation variance in which is selected.
[...]
Proposed resolution (June, 2014):
This issue is resolved by the resolution of issue
1467.
Which as per the resolution was resolved via CWG 1467:
1467. List-initialization of aggregate from same-type object
[...]
Proposed resolution (June, 2014):
[...]
Move the final bullet of 16.3.3.2 [over.ics.rank] paragraph 3 to the beginning of the list and change it as follows:
[...]
even if one of the other rules in this paragraph would otherwise apply. [Example: ... — end example]
This resolution also resolves issues 1490, 1589, 1631, 1756, and 1758.
Particularly by re-ording the [over.ics.rank]/3 such that [over.ics.rank]/3.1 now applies for the OP's case, and takes precedence over the other rules of [over.ics.rank]/3:
List-initialization sequence L1 is a better conversion sequence than
list-initialization sequence L2 if
(3.1.1) L1 converts to std::initializer_list<X> for some X and L2 does not, or, if not that
(3.1.2) [...]
even if one of the other rules in this paragraph would otherwise apply.
Compilers such as GCC and Clang has since back-ported DR 1467 to earlier standards (C++11 and C++14); Clang specifically as of Clang 3.7, and we can verify the CWG 1589 connection to OP's example as it is rejected by Clang 3.6 but accepted by Clang 3.7 (DEMO).
MSVC, on the other, has seemingly has not implemented this change even as per the updated C++17 standard where it is no longer "just a" DR.
|
70,967,545 | 70,967,720 | Why can you create typedefs to a struct that doesn't exist? | The following code compiles fine.
header.h:
typedef struct Placeholder_Type* Placeholder;
impl.cpp:
#include "header.h"
void doSomething(Placeholder t) {
(void) t;
}
int main() {
int *a = new int();
doSomething((Placeholder)a);
}
compilation command:
clang++ impl.cpp
The type Placeholder_Type does not exist anywhere and it doesn't exist as a symbol in the output binary.
Why is it legal to create a typedef for a type that does not exist?
Why can I create a function using a type that doesn't exist?
Is this equivalent to just using void* but named "Placeholder"?
| struct Placeholder_Type declares the struct Placeholder_Type (but doesn't define it), no matter where it appears. Even if it's inside a typedef. So you don't create a typedef to a struct that doesn't exist, but to one you just declared (and thus created, if the compiler didn't already know about it).
As for why, it's because this way you can keep the definition of a struct away from the public interface. For example, this is a typical way to implement an opaque object in C:
// mytype.h
typedef struct MytypeImpl* Mytype;
Mytype create_mytype();
void destroy_mytype(Mytype o);
void do_something_with_mytype(Mytype o, int i);
// mytype.c
struct MytypeImpl {
int something;
int otherthing;
};
Mytype create_mytype() {
Mytype o = malloc(sizeof(*o));
o->something = 0;
o->otherthing = 0;
return o;
}
void destroy_mytype(Mytype o) {
free(o);
}
// etc.
Individual styles may differ in details, of course. But the key point is that the definition of the struct isn't visible outside mytype.c, so nobody can just access the data members.
|
70,967,789 | 70,967,816 | Why can we use uninitialized variables in C++? | In programming languages like Java, C# or PHP we can't use uninitialized variables. This makes sense to me.
C++ dot com states that uninitialized variables have an undetermined value until they are assigned a value for the first time. But for integer case it's 0?
I've noticed we can use it without initializing and the compiler shows no error and the code is executed.
Example:
#include <iostream>
using namespace std;
int main()
{
int a;
char b;
a++; // This works... No error
cout<< a << endl; // Outputs 1
// This is false but also no error...
if(b == '0'){
cout << "equals" << endl;
}
return 0;
}
If I tried to replicate above code in other languages like C#, it gives me compilation error. I can't find anything in the official documentation.
I highly value your help.
| C++ gives you the ability to shoot yourself in the foot.
Initialising an integral type variable to 0 is a machine instruction typically of the form
REG XOR REG
Its presence is less than satisfactory if you want to initialise it to something else. That's abhorrent to a language that prides itself on being the fastest. Your assertion that integers are initialised to zero is not correct.
The behaviour of using an uninitialised variable in C++ is undefined.
|
70,967,924 | 70,968,805 | Recursive wrapper that adds a specific function applied to every objects in a container of container in c++ | I would like to make a wrapper to a specific container (or a container of container) class such that the wrapper (1) inherits all the functions of the parent class and (2) adds a specific function that applies to all the elements.
For example, I want to add bar function that takes an object whose class is Destination on the container types that have bar(Destination). The first thing that comes to my mind is as below:
// I want as Enablebar<vector<Foo>> for any `Foo` that is guaranteed to have `void bar(Destination)`.
template <class Iterable> class Enablebar : public Iterable {
public:
void bar(const Destination &dest) {
for (auto &item : *this) {
item.bar(dest);
}
}
};
So that I can enable bar functions on various containers in a project. (I cannot modify or touch the definitions of the containers, and there are many of such containers).
The problem is that I would like to use it also on container of container, or even container of container of container (i.e., vector<vector<list<Foo>>>), where Foo and vector are classes that I cannot touch or modify. So I just use it like Enablebar<vector<Enablebar<vector<Enablebar<list<Foo>>>>.
Question: is it possible to write a somewhat recursive, smart wrapper that replaces Enablebar that I can use something like:
EnablebarSmartly<vector<vector<list<Foo>>>>? I'm not having a problem with EnableBar; just out of curiosity.
| With 2 overloads, you might do something like:
template <typename T>
auto bar(T& item, const Destination &dest)
-> decltype(item.bar(dest), void())
{
item.bar(dest);
}
template <typename Container>
auto bar(Container& c, const Destination &dest)
-> decltype(c.begin(), void()) // Check container, just use `begin` here
{
for (auto &item : c) {
bar(item, dest);
}
}
With C++20, You might use requires instead of SFINAE
template <typename T>
void bar(T& item, const Destination &dest)
requires(requires{ item.bar(dest);})
{
item.bar(dest);
}
template <typename Container>
void bar(Container& c, const Destination &dest)
requires(requires{c.begin(); /* Check container, just use `begin` here*/ })
{
for (auto &item : c) {
bar(item, dest);
}
}
|
70,968,143 | 70,968,305 | Generate all balanced parenthesis for a given N | // Header files
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
// This function checks for well formedness of the passed string.
bool valid(string s)
{
stack<char> st;
for(int i=0;i<s.length();i++)
{
char x=s[i];
if(x=='(')
{
st.push(x);
continue;
}
if(st.empty())
return false;
st.pop();
}
return st.empty();
}
// This function generates all combination of parenthesis and only checks well formedness of string whose length is equal to n.
void generate(int n,string s)
{
if(s.length()==n)
{
bool balanced = valid(s);
if(balanced)
cout<<s<<endl;
return;
}
generate(n,s+"(");
generate(n,s+")");
}
// Driver code
int main()
{
int n;
cin>>n;
generate(n,"");
return 0;
}
What i am trying to achieve is to generate all possible parenthesis of upto length n. And check well formedness/ balance of the so formed strings whose size is N. My program terminates without printing anything. Please help!
Eg for n=3,
Input:
N = 3
Output:
((()))
(()())
(())()
()(())
()()()
Order does not matter.
My output doesn't show anything.
Refer : https://practice.geeksforgeeks.org/problems/generate-all-possible-parentheses/1
| //c++ program to print all the combinations of
balanced parenthesis.
#include <bits/stdc++.h>
using namespace std;
//function which generates all possible n pairs
of balanced parentheses.
//open : count of the number of open parentheses
used in generating the current string s.
//close : count of the number of closed
parentheses used in generating the current string
s.
//s : currently generated string/
//ans : a vector of strings to store all the
valid parentheses.
void generateParenthesis(int n, int open, int
close, string s, vector<string> &ans){
//if the count of both open and close
parentheses reaches n, it means we have generated
a valid parentheses.
//So, we add the currently generated string s
to the final ans and return.
if(open==n && close==n){
ans.push_back(s);
return;
}
//At any index i in the generation of the
string s, we can put an open parentheses only if
its count until that time is less than n.
if(open<n){
generateParenthesis(n, open+1, close, s+"{",
ans);
}
//At any index i in the generation of the string
s, we can put a closed parentheses only if its
count until that time is less than the count of
open parentheses.
if(close<open){
generateParenthesis(n, open, close+1, s+"}",
ans);
}
}
int main() {
int n = 3;
//vector ans is created to store all the
possible valid combinations of the parentheses.
vector<string> ans;
//initially we are passing the counts of open
and close as 0, and the string s as an empty
string.
generateParenthesis(n,0,0,"",ans);
//Now, here we print out all the combinations.
for(auto s:ans){
cout<<s<<endl;
}
return 0;
}
|
70,968,504 | 70,969,516 | How do I constrain the parameter(s) of a functor using concepts? | I have the following concept:
template <typename T>
concept FunctorInt = requires(T a, int b) {
a.operator()(b); //require the () operator with a single int parameter.
};
I use this in the following function:
template <FunctorInt functor_t>
void for_each_sat_lit(const int ClauseIndex, functor_t functor) {
auto LitIndex = -1;
uint32_t Count = h_SatisfiedLitCount[ClauseIndex];
if constexpr (!satlit) { Count = h_LiteralsInClauseCount[ClauseIndex] - Count; }
for (uint32_t dummy = 0; dummy < Count; dummy++) {
LitIndex = NextSetBit(h_SATLiteralBits[ClauseIndex], LitIndex);
functor(LitIndex); //LitIndex must be an int.
}
}
This compiles. However, when I try and break the code by changing the concept to
template <typename T>
concept FunctorInt = requires(T a, float b) {
a.operator()(b); //I intend to require the () operator with a single float parameter.
};
It still compiles, meaning it did not constrain the functor at all.
How do I constrain a functor so that it can only have a single int parameter?
MSVC: concepts.cpp
#include <concepts>
template <typename T>
concept FunctorInt = requires(T a, int b) {
a.operator()(b); //require the () operator with a single int parameter.
};
template <typename T>
concept FunctorFloat = requires(T a, float b) {
a.operator()(b); //require the () operator with a single float parameter.
};
void Loop(FunctorInt auto functor) {
for (auto i = 0; i < 10; i++) {
functor(i);
}
}
void LoopShouldNotCompile(FunctorFloat auto functor) {
for (auto i = 0; i < 10; i++) {
functor(i); //<< i is not a float.
}
}
int main(const int argc, const char* argv[]) {
Loop( [](int a){ printf("%i", a); });
LoopShouldNotCompile([](float a){ printf("%f", a); });
}
If I change the definitions of FunctorInt and FunctorFloat using std::invocable, the same problem persists:
concept FunctorInt = std::invocable<int>;
concept FunctorFloat = std::invocable<float>;
Everything still compiles, whereas it should give a compile error on LoopShouldNotCompile.
UPDATE:
I settled on:
template <typename T>
concept FunctorInt =
requires() { [](void(T::*)(int) const){}(&T::operator()); }
|| requires() { [](void(T::*)(int) ){}(&T::operator()); };
Which creates a functor that only allows a single int parameter and doesn't care about const-correctness.
| Your concept check if the type can be called with an int
but you cannot control promotion/conversion which happens before.
You can check signature of T::operator(), but then previous valid cases (as overload, template function, no exact function but similar (const, volatile, ...)) might no longer work.
For example:
template <typename T>
concept FunctorInt = requires() {
[](void(T::*)(int) const){}(&T::operator());
};
void Loop(FunctorInt auto functor) { /**/ }
int main() {
Loop([](int a){ printf("%i", a); });
Loop([](float a){ printf("%f", a); }); // Not compile
}
Demo
|
70,968,854 | 71,429,252 | Using ADTF File Library | I wanted to use ADTF library in my visual studio project. Do i need to build the library from my machine to use it? The instructions provided with the library are not clear to me since i haven't used cmake build before.
Any help in this regard is greatly appreciated.
| The following instructions are for ADTF File Library 0.7:
Linux
First build a_util
$ cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=<any-install-dir> -Da_util_cmake_enable_documentation=OFF -Da_util_cmake_enable_integrated_tests=OFF . && make && make install
Then build ddl
$ cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=<any-install-dir> -Da_util_DIR=<a_util-install-dir-given-above> -Dddl_cmake_enable_documentation=OFF -Dddl_cmake_enable_tests=OFF -Dddl_cmake_enable_generator_tools=OFF -Dddl_cmake_enable_installation=ON . && make && make install
Then build ifhd
$ cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=<any-install-dir> -Da_util_DIR=<a_util-install-dir-given-above> -Dddl_DIR=<ddl-install-dir-given-above> -Difhd_cmake_enable_documentation=OFF -Difhd_cmake_enable_integrated_tests=OFF . && make && make install
Windows
cmake steps remain the same. It will generate visual studio solution that you can use to build and edit.
|
70,969,000 | 70,969,209 | Function to return median of 3 | I am looking for the best solution to finding a median of 3. I want it to be in the least lines possible. Thank you in advance :) I've tried sth like this:
int median(int a, int b, int c)
{
if ((a >= b && a <= c) || (a <= b && a >= c)) return a;
if ((b >= a && b <= c) || (b <= a && b >= c)) return b;
return c;
}
I believe this solution is okay, but maybe there is something better?
| int median(int a, int b, int c)
{
return ((b > a) == (a > c)) ? a : ((a > b) == (b > c)) ? b : c;
}
https://godbolt.org/z/4G3dzPcs3
Above code has small bug in it (prove that tests are important), here is fixed version:
int median(int a, int b, int c)
{
return (b > a) == (a > c) ? a : (b > a) != (b > c) ? b : c;
}
https://godbolt.org/z/8bq38hvaj (contains testcase reviling bug in earlier code).
|
70,969,326 | 70,969,441 | how to use parallelize two serial for loops such that the work of the two for loops are distributed over the thread | I have written the below code to parallelize two 'for' loops.
#include <iostream>
#include <omp.h>
#define SIZE 100
int main()
{
int arr[SIZE];
int sum = 0;
int i, tid, numt, prod;
double t1, t2;
for (i = 0; i < SIZE; i++)
arr[i] = 0;
t1 = omp_get_wtime();
#pragma omp parallel private(tid, prod)
{
tid = omp_get_thread_num();
numt = omp_get_num_threads();
std::cout << "Tid: " << tid << " Thread: " << numt << std::endl;
#pragma omp for reduction(+: sum)
for (i = 0; i < 50; i++) {
prod = arr[i]+1;
sum += prod;
}
#pragma omp for reduction(+: sum)
for (i = 50; i < SIZE; i++) {
prod = arr[i]+1;
sum += prod;
}
}
t2 = omp_get_wtime();
std::cout << "Time taken: " << (t2 - t1) << ", Parallel sum: " << sum << std::endl;
return 0;
}
In this case the execution of 1st 'for' loop is done in parallel by all the threads and the result is accumulated in sum variable. After the execution of the 1st 'for' loop is done, threads start executing the 2nd 'for' loop in parallel and the result is accumulated in sum variable. In this case clearly the execution of the 2nd 'for' loop waits for the execution of the 1st 'for' loop to get over.
I want to do the processing of the two 'for' loop simultaneously over threads. How can I do that? Is there any other way I can write this code more efficiently. Ignore the dummy work that I am doing inside the 'for' loop.
| You can declare the loops nowait and move the reduction to the end of the parallel section. Something like this:
# pragma omp parallel private(tid, prod) reduction(+: sum)
{
# pragma omp for nowait
for (i = 0; i < 50; i++) {
prod = arr[i]+1;
sum += prod;
}
# pragma omp for nowait
for (i = 50; i < SIZE; i++) {
prod = arr[i]+1;
sum += prod;
}
}
|
70,969,514 | 70,970,696 | Variadic Template Specialization Overload works in GCC but not MSVC | I have the following function declarations
template<typename RET, typename... PARAMS>
RET Execute(PARAMS... params)
{ ... }
template<typename RET>
RET Execute()
{ ... }
template<typename... PARAMS>
void Execute(PARAMS... params)
{ ... }
void Execute();
These calls work fine in both GCC and MSVC
Execute<int32_t>(static_cast<int8_t>(0), static_cast<int32_t>(0))
Execute<int32_t>()
Execute(static_cast<uint8_t>(0))
Execute()
This call works fine in GCC, but not in MSVC. I get an error for an ambiguous call to overload function. Just because the return type is the same as the first parameter.
Execute<int32_t>(static_cast<int32_t>(0), static_cast<int32_t>(0))
Considering it is not possible to explicitly give the typenames of the parameter pack, it is not ambiguous. Why does MSVC seem to have this wrong? Is there anyway to fix this?
|
This call works fine in GCC, but not in MSVC.
In my Debian stable, I get the same error also with clang++ 11.0.1-2 ("error: call to 'Execute' is ambiguous") and g++ 10.2.1 (" error: call of overloaded ‘Execute<int32_t>(int32_t, int32_t)’ is ambiguous").
Considering it is not possible to explicitly give the typenames of the parameter pack
Not exactly: you can explicit the typenames of the arguments or the types of the first arguments; this permit to overrides the typenames deduction from the arguments.
Why does MSVC seem to have this wrong?
My question is: why your g++ seems to have this right?
Is there anyway to fix this?
Yes, a very simple way: add a variadic list of non-types template parameter before the variadic list of the argument types.
I mean, write the third Execute() as follows
template <int..., typename... PARAMS>
void Execute (PARAMS... params)
{ /* ... */ }
and maybe also the first one as follows
template <typename RET, int..., typename... PARAMS>
RET Execute (PARAMS... params)
{ /* ... */ }
This way you impose the PARAMS types deduction from the params and a explicit template parameter is necessarily the return type (when you can express it).
|
70,969,783 | 70,970,200 | How to print all inputs of string from a for loop? | Printing the names that I inputted in the variable userInput only prints the last name that I inputted and not including the first one that I inputted.
If my programming was incorrect please explain what should I do in a way that beginners could understand.
int main()
{
int data = 0;
int input;
string userInput;
//this program will run repeatedly when user didn't enter a number from 1 to 10 only
while (data == 0)
{
cout << "Enter number of data: ";
cin >> data;
if (!(data > 0 || data < 11))
{
data = 0;
}
else
{
//this program will repeat depends on the input from the variable of data
for (input = 0; input < data; input++)
{
cout << "Enter student name: ";
cin >> userInput;
}
}
}
cout << "Student names" << endl;
//this for loop shoul print all names that was inputted in the variable userInput
for (in = 0; insert < data; insert++)
{
cout << userInput << endl;
}
return data;
}
Output
Enter number of data: 0 //the program will repeat when the user didn't input number from 1 to 10 only
Enter number of data: 3 //the program will ask for names according to the input in this line
Enter students name: Jack
Enter students name: King
Enter students name: Queen
Student names
Queen
Queen
Queen
//The output should look like this
Student names
Jack
King
Queen
| As already mentioned you are just overwriting userInput with each new input read. You can simply append the new string to your existing one:
std::string students;
for (int i=0; i<data; ++it) {
std::string input;
std::cout << "Enter student name: ";
std::cin >> input;
if (!students.empty())
students += "\n";
students += input;
}
But I also highly recommend to use std::vector<std::string> in this case since it would be a mess to extract the student names afterwards from such a concatenated string and you can't use any of the helpful functions these containers provide.
std::vector<std::string> students;
for (int i=0; i<data; ++it) {
std::string input;
std::cout << "Enter student name: ";
std::cin >> input;
students.push_back(input);
}
// one example of the advantages
std::cout << "Number of students: " << students.size() << std::endl;
And printing when using vector:
for (auto it = students.begin(); it != students.end(); ++it) {
std::cout << *it << std::endl;
}
|
70,970,886 | 70,971,036 | C++ endl not printing new line when called from a method | New to C++
My understanding is endl will add a new line. So with the following piece of code:
#include <iostream>
using namespace std;
void printf(string message);
int main()
{
cout << "Hello" << endl;
cout << "World" << endl;
printf("Hello");
printf("World");
return 0;
}
void printf(string message) {
cout << message << endl;
}
I expect the output to be:
Hello
World
Hello
World
But, strangely, the output is:
Hello
World
HelloWorld
Looks like, when called from the user-defined method, endl is not adding new line..??
What is wrong with my understanding here. Please advise.
| The problem is that due to overload resolution the built in printf function is selected over your custom defined printf function. This is because the string literal "Hello" and "World" decays to const char* due to type decay and the built in printf function is a better match than your custom defined printf.
To solve this, replace the printf calls with :
printf(std::string("Hello"));
printf(std::string("World"));
In the above statements, we're explicitly using std::string's constructor to create std::string objects from the string literal "Hello" and "World" and then passing those std::string objects by value to your printf function.
Another alternative is to put your custom printf inside a custom namespace. Or you can name your function other than printf itself.
|
70,970,959 | 70,972,329 | nested if v/s && operator | I am writing code in C++ for checking if a cycle is present in a given undirected graph or not.
My code is this:-
#include <bits/stdc++.h>
using namespace std;
// Class for an undirected graph
class Graph
{
// No. of vertices
int V;
// Pointer to an array
// containing adjacency lists
list<int> *adj;
bool isCyclicUtil(int v, bool visited[], int parent);
public:
// Constructor
Graph(int V);
// To add an edge to graph
void addEdge(int v, int w);
// Returns true if there is a cycle
bool isCyclic();
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
// Add w to v’s list.
adj[v].push_back(w);
// Add v to w’s list.
adj[w].push_back(v);
}
// A recursive function that
// uses visited[] and parent to detect
// cycle in subgraph reachable
// from vertex v.
bool Graph::isCyclicUtil(int v, bool visited[], int parent)
{
// Mark the current node as visited
visited[v] = true;
// Recur for all the vertices
// adjacent to this vertex
for(int i:adj[v])
{
// If an adjacent vertex is not visited,
//then recur for that adjacent
// if ((!visited[i])&&(isCyclicUtil(i, visited, v))) // 1st block
// {
// return true;
// }
if (!visited[i]) { // 2nd block
if (isCyclicUtil(i, visited, v)) {
return true;
}
}
// If an adjacent vertex is visited and
// is not parent of current vertex,
// then there exists a cycle in the graph.
else if (i != parent)
return true;
}
return false;
}
// Returns true if the graph contains
// a cycle, else false.
bool Graph::isCyclic()
{
// Mark all the vertices as not
// visited and not part of recursion
// stack
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Call the recursive helper
// function to detect cycle in different
// DFS trees
for (int u = 0; u < V; u++)
{
// Don't recur for u if
// it is already visited
if (!visited[u])
if (isCyclicUtil(u, visited, -1))
return true;
}
return false;
}
// Driver program to test above functions
int main()
{
Graph g1(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(2, 1);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
g1.isCyclic()?
cout << "Graph contains cycle\n":
cout << "Graph doesn't contain cycle\n";
Graph g2(3);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
g2.isCyclic()?
cout << "Graph contains cycle\n":
cout << "Graph doesn't contain cycle\n";
Graph g3(4);
g3.addEdge(1, 2);
g3.addEdge(2, 3);
g3.isCyclic()?
cout << "Graph contains cycle\n":
cout << "Graph doesn't contain cycle\n";
return 0;
}
There are two labeled blocks in this code namely block 1 and block 2.
This code outputs correctly when I use the second block.
But if I use first block instead of the 2nd block It prints something different.
My question is that Are the first block and second block code use different logic?
If not then why block 1 prints different from 2nd block?
| Think about the negation of your condition, as this affects when the else branch is executed.
In the commented-out code, it is
!(!visited[i] && isCyclicUtil(i, visited, v))
which is
visited[i] || !isCyclicUtil(i, visited, v)
and your entire conditional, testing the negated condition first, is equivalent to
if (visited[i] || !isCyclic(i, visited, v)) {
if (i != parent)
return true;
}
else {
return true;
}
In the "live" code, the negation is
!(!visited[i])
which is
visited[i]
and the entire conditional is equivalent to
if (visited[i]) {
if (i != parent) {
return true;
}
}
else if (isCyclicUtil(i, visited, v)) {
return true;
}
|
70,971,282 | 70,971,706 | Generate Integer Sequence For Template Parameter Pack | There is a class method template with parameter pack I want to call, defined as:
class C {
template<int ... prp> void function() {}
}
For a given integer N, I need all integers up to N as template arguments for the parameter pack.
constexpr int N = 2;
C c;
c.function<0, 1>();
I have tried using std::integer_sequence, but it can't be used here.
c.function<std::make_integer_sequence<int, N>>();
I also found this answer: Passing std::integer_sequence as template parameter to a meta function Could I pass the function inside the partial specialization, e.g. using std::function? I was not able to use template arguments with std::function.
Additionally, the class has multiple function I would like to call the same way.
c.function1<0, 1>();
c.function2<0, 1>();
There must be a nice way to solve this but I wasn't successful yet. Still trying to understand TMP.
| You might create helper function:
template <int... Is>
void helper(C& c, std::integer_sequence<int, Is...>)
{
c.function1<Is...>();
c.function2<Is...>();
}
And call it
constexpr int N = 2;
C c;
helper(c, std::make_integer_sequence<int, N>());
|
70,971,668 | 71,037,938 | How to include libgmp to xeus-cling? | I am trying to run the following code:
#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmpxx.so")
#include <gmpxx.h>
and I get following errors:
In file included from input_line_8:1:
In file included from /usr/include/gmpxx.h:44:
In file included from /usr/include/x86_64-linux-gnu/gmp.h:56:
In file included from /usr/include/limits.h:26:
/usr/include/x86_64-linux-gnu/bits/libc-header-start.h:56:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_BFP_EXT) || __GLIBC_USE (ISOC2X)
^
/usr/include/x86_64-linux-gnu/bits/libc-header-start.h:73:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_FUNCS_EXT) || __GLIBC_USE (ISOC2X)
^
In file included from input_line_8:1:
In file included from /usr/include/gmpxx.h:44:
In file included from /usr/include/x86_64-linux-gnu/gmp.h:56:
/usr/include/limits.h:145:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_BFP_EXT_C2X)
^
I am trying to include <limits.h> firstly:
#include <limits.h>
#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmpxx.so")
#include <gmpxx.h>
but I still get the error
In file included from input_line_9:1:
In file included from /usr/include/gmpxx.h:44:
In file included from /usr/include/x86_64-linux-gnu/gmp.h:56:
/usr/include/limits.h:145:5: error: function-like macro '__GLIBC_USE' is not defined
#if __GLIBC_USE (IEC_60559_BFP_EXT_C2X)
^
How to make <libgmpxx.h> use <limits.h> from xeus-cling, not from /usr/include?
| in jupyter:
#include <stddef.h> /* for size_t */
#include <limits.h>
#define __xeus_cling__
#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmpxx.so")
#include <gmpxx.h>
and
in /usr/include/x86_64-linux-gnu/gmp.h
#include <stddef.h> /* for size_t */
#include <limits.h>
replace with
#ifndef __xeus_cling__
#include <stddef.h> /* for size_t */
#include <limits.h>
#endif
|
70,971,977 | 70,972,386 | CMake - Library with example subdirectory running as separate project | Edit 2 - Fixed!
The issue was fixed by correctly using absolute paths rather than relative paths, and by adding add_subdirectory to example/CMakelists.txt.
I have updated the provided code (and will leave the repository in case somebody wants to use it as a starting point.
Edit:
Adjusted CMakelists.txt files to use absolute paths only (as per recommendation from @Tsyvarev
Added exact compilation error message
Original post:
I am trying to write a library, that contains example project, and can be added as a Git submodule. The desired structure would be this:
- source
- MyLib
lib.cpp
- CMakelists.txt
- include
- MyLib
lib.h
- example
main.cpp
CMakelists.txt
CMakelists.txt (main CMake for library)
What am I trying to achieve:
The structure should probably more or less stay, so one can install the library just by adding a gitmodule
The example project should be capable of running on its own by loading the CMakelists.txt in the directory, and should be able to use the library
What is my problem:
My biggest problem is linking the example to the library which lives in a sibling folder, and make sure it compiles. I managed to write a CMakelists.txt in a way that my IDE understands #include statements correctly, but during compilation the function definitions are not found.
Could anyone provide some pointers, please?
Exact compilation error message:
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lMY_LIB
collect2.exe: error: ld returned 1 exit status
mingw32-make[3]: *** [CMakeFiles\MY_LIB_EXAMPLE.dir\build.make:95: MY_LIB_EXAMPLE.exe] Error 1
mingw32-make[2]: *** [CMakeFiles\Makefile2:82: CMakeFiles/MY_LIB_EXAMPLE.dir/all] Error 2
mingw32-make[1]: *** [CMakeFiles\Makefile2:89: CMakeFiles/MY_LIB_EXAMPLE.dir/rule] Error 2
mingw32-make: *** [Makefile:123: MY_LIB_EXAMPLE] Error 2
CMakelists.txt files
CMakelists.txt:
cmake_minimum_required(VERSION 3.20)
set(CMAKE_CXX_STANDARD 20)
project(MY_LIB)
add_subdirectory(source)
source/CMakelists.txt
add_library(MY_LIB MyLib/library.cpp ../include/MyLib/library.h)
target_include_directories(MY_LIB PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/MyLib)
target_include_directories(MY_LIB PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/source/MyLib)
example/CMakelists.txt
cmake_minimum_required(VERSION 3.20)
set(CMAKE_CXX_STANDARD 20)
#--------------------------------------------------------------------
# Get solution root
#--------------------------------------------------------------------
cmake_path(GET CMAKE_CURRENT_SOURCE_DIR PARENT_PATH LIB_PATH)
cmake_path(SET LIB_INCLUDE_PATH "${LIB_PATH}/include")
message(${LIB_PATH})
message(${LIB_INCLUDE_PATH})
#--------------------------------------------------------------------
# Set project name
#--------------------------------------------------------------------
project(MY_LIB_EXAMPLE)
#--------------------------------------------------------------------
# Add source
#--------------------------------------------------------------------
add_executable(MY_LIB_EXAMPLE main.cpp)
add_subdirectory(${LIB_PATH} library-build)
#--------------------------------------------------------------------
# Link libraries
#--------------------------------------------------------------------
target_link_libraries(MY_LIB_EXAMPLE MY_LIB)
#--------------------------------------------------------------------
# Link include directories
#--------------------------------------------------------------------
target_include_directories(MY_LIB_EXAMPLE PUBLIC ${LIB_INCLUDE_PATH})
I created a sample repository with my setup: https://github.com/jiriKralovec/cmake-library
|
he example project should be capable of running on its own by loading the CMakelists.txt in the directory, and should be able to use the library
Just add:
add_subdirectory(./../ some_unique_name_here)
I think I would remove source/CMakelists.txt and write it all in root CMakelists.txt. It's odd to use ../ to refer to include directories.
I suggest doing options and/or unit tests:
root CMakeLists.txt:
include(CTest)
add_library(MY_LIB ....)
# one design
if (BUILD_TESTING)
add_subdirectory(example)
endif()
# another design
add_subdirectory(utilities)
example/CMakeLists.txt:
# if it is something simple, add unit test:
add_executable(MY_LIB_EXAMPLE1 <maybe EXCLUDE_FROM_ALL?> ...)
add_test(NAME MY_LIB_EXAMPLE1 COMMAND MY_LIB_EXAMPLE1)
utilities/CMakeLists.txt:
# if it is a utility, optionally build it
add_executable(MY_LIB_UTILITY_TO_DO_SMTH ...)
option(... BUILD_MY_LIB_UTILITY_TO_DO_SMTH OFF)
if(NOT BUILD_MY_LIB_UTILITY_TO_DO_SMTH)
set_target_properties(
MY_LIB_UTILITY_TO_DO_SMTH
PROPERTIES EXCLUDE_FROM_ALL ON
)
endif()
Either way, do one CMake build. Then if user wants to build the utility, he will do cmake --build <builddir> --target MY_LIB_UTILITY_TO_DO_SMTH (or make MY_LIB_UTILITY_TO_DO_SMTH). If you would want to build unit tests, you would do cmake ... -D BUILD_TESTING=1.
Some people add all unit tests executables as EXCLUDE_FROM_ALL and make special add_custom_target(build_tests) add_target_dependencies(build_tests MY_LIB_EXAMPLE1 etc. etc.) and build that custom target before testing.
|
70,971,989 | 70,972,054 | In C++, why are my variable inputs that are separated by a space being stored incorrectly? | In this code I ask the user for inputs separated by a space, gradeOne space gradeTwo.
However, it is not functioning as intended so I added output statements at the end to see if the values were stored correctly.
If I type in: 59 95 gradeOne should be 59, temp should be ' ' and gradeTwo should be 95 but the output says gradeOne is 59, temp is 9 and gradeTwo is 5. What is happening? Thank you for any help!
#include <iostream>
using namespace std;
int main()
{
int gradeOne, gradeTwo;
char temp;
cout<<"Please enter 2 grades, separated by a space: ";
cin>>gradeOne>>temp>>gradeTwo;
if(gradeOne < 60 && gradeTwo < 60)
cout<<"Student Failed:("<<endl;
else if(gradeOne >= 95 && gradeTwo >= 95)
cout<<"Student Graduated with Honors:)"<<endl;
else
cout<<"Student Graduated!"<<endl;
cout<<gradeOne<<endl;
cout<<gradeTwo<<endl;
cout<<temp<<endl;
return 0;
}
| operator >> automatically skip space. Just change to:
cin>>gradeOne>>gradeTwo;
|
70,972,111 | 70,972,379 | Why can I go out of bounds with the assignment opeator but not with the {} | My question is pretty straightfoward: why can I assign a value that goes out of bounds to an array like this, but not with the {} operator:
int arr[2];
arr[2] = 2;
for(int num{0}; num < 3; num++)
cout << arr[num] << endl;
But when I do this I get an error right from the start:
int arr[2] {1,2,3};
Now I know that assigning a value beyond the scope of the array may cause an undefinied behavior, as this questions has clarified to me:
Accessing an array out of bounds gives no error, why?
But why can't I go beyond the arrays' limit in the second case? Even though it is wrong - And I don't intend to do it - I'd like to know the difference in these cases.
| Both cases are completly different. The first one is array element assignement. The second is array initialization. The rules state that it is an error if you provide more initializers that the array can hold. The rules state also, that element access behind the array end is not an error but undefined behaviour. In other languages, there is bound checking at runtime for array access, but not in C++. So the reason it behaves like it does, is that the C++ standard commitee decided so.
You could of course ask why the C++ standard commitee decided so. I think the answer is, that C++ tries to be as backward compatible as possible and the rules for array element access have always been that way.
Also the initialization can be evaluated and checked at compile time, whereas the element access happens during runtime and the compiler cannot foresee if there is actually an access behind the end of the array.
|
70,972,244 | 70,972,545 | c++ - structure in map allocation | As I known, map value is initialized by NULL(0). However, Below code is works well without any allocation. How is this code work?
#include<bits/stdc++.h>
using namespace std;
struct stuc{
map<string, stuc> mp;
int cnt;
}root;
int main() {
stuc* u = &root;
stuc* v = &(u->mp["test"]); // how to allocate?
cout << v->cnt << endl;
return 0;
}
| If you access a map with the [] operator like in
&(u->mp["test"])
there is a new key value pair allocated, default initialized, and inserted into the map if the element does not already exists [1]. In your program that is exactly what happens. The map does not already have an key "test". Thus a new value is default constructed. Because you did not define a custom default constructor for your stuc struct, all its members are default initialized (mp = {} and cnt = 0). This is the reason why you get 0 if you read the cnt member of the newly created value.
[1] https://en.cppreference.com/w/cpp/container/map/operator_at
|
70,973,253 | 70,983,377 | Ignore exceptions on Boost.Log when unable to create folder | This is a snippet of code that I have to maintain:
std::string log_file_name = "/tmp/log/program.log";
auto fs_sink = boost::log::add_file_log( boost::log::keywords::file_name = log_file_name, boost::log::keywords::open_mode = std::ios_base::app );
boost::log::add_common_attributes( );
fs_sink->locked_backend( )->auto_flush( true );
BOOST_LOG_TRIVIAL(info) << "Program Init...";
It's works fine, but when the program is unable to create the /tmp/log/ folder (e.g: there is already a file called /tmp/log), it throws an exception in BOOST_LOG_TRIVIAL
Error - Terminating - Exception: boost::filesystem::create_directory: Not a directory: "/tmp/log"
terminate called after throwing an instance of 'boost::filesystem::filesystem_error'
what(): boost::filesystem::create_directory: Not a directory: "/tmp/log"
Is it possible to gracefully ignore when such a situation happens, without throwing an exception?
| You can set an exception handler on sink, core or logger level. The handler will be called when an exception is propagated through the given component, and in particular it may suppress further propagation of the exception. For example, to suppress all exceptions on the core level, you can set it like this:
boost::log::core::get()->set_exception_handler(boost::log::make_exception_suppressor());
|
70,973,619 | 70,973,707 | How to constrain an auto lambda parameter to a pointer to member function? | I have a generic lambda function that needs to accept a pointer-to-member-function as a parameter. I can of course simply use auto on its own and the compiler will deduce the correct type. However, where possible, I prefer to decorate my auto parameters with *, & and const where appropriate, thus better communicating the nature and intent of the deduced type. If I simply make the auto parameter an auto*, I get a compiler error, which I'm not really surprised by as auto* signifies a regular pointer, not a pointer-to-member. Is there some syntax for constraining an auto parameter to accept a pointer-to-member, or should I just use auto and forget about it?
int main()
{
struct S { void m() {} };
//auto l = [](auto* pmf) // ERROR
//auto l = [](const auto& pmf) // Works, but uh, bit misleading I think
auto l = [](auto pmf)
{
S s;
(s.*pmf)();
};
l(&S::m);
}
| You can declare it as:
auto l = [](auto S::*pmf)
It does tie the pointer to a S type, but it makes sense because it is that way you will use it.
|
70,973,923 | 70,984,846 | ECDSA signature verification: Go vs OpenSSL | I'm trying to verify an ECDSA signature for a hash using a public key. I've written a small Go program that successfully does this but I've been unable to port it to C++.
Here is my input data:
Public key: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDd9VXmpHjV4voFO+0ZoFPlRr5icZXquxsr9EkaOUO9B7Wl1DAgGI0EKCm1++Bl2Od32xZFeFuG07OTpTMVOCPA==
Hash: 562d6ddfb3ceb5abb12d97bc35c4963d249f55b7c75eda618d365492ee98d469
Signature: 304502204d6d070117d445f4c2fcdbd4df037a1c8cfee2a166353c2e562cd5efd06e914d022100bb06439ded1478bd19022519dc06a84ba18ea4bf30ea9eb9ea90f8b66dad12c7
Here is my working go program:
package main
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/base64"
"encoding/hex"
)
func main() {
key_, _ := base64.StdEncoding.DecodeString("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDd9VXmpHjV4voFO+0ZoFPlRr5icZXquxsr9EkaOUO9B7Wl1DAgGI0EKCm1++Bl2Od32xZFeFuG07OTpTMVOCPA==")
key, _ := x509.ParsePKIXPublicKey(pkey_)
msg, _ := hex.DecodeString("562d6ddfb3ceb5abb12d97bc35c4963d249f55b7c75eda618d365492ee98d469")
sig, _ := hex.DecodeString("304502204d6d070117d445f4c2fcdbd4df037a1c8cfee2a166353c2e562cd5efd06e914d022100bb06439ded1478bd19022519dc06a84ba18ea4bf30ea9eb9ea90f8b66dad12c7")
valid := ecdsa.VerifyASN1(key.(*ecdsa.PublicKey), msg[:], sig)
if !valid {
panic("key invalid")
}
}
And here is my broken C++ program that fails at the very last assertion. I'd like to know why that is:
#include <cassert>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <openssl/bio.h>
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
std::string decode_hex_str(std::string const &hex) {
std::string str;
for (std::size_t i { 0 }; i < hex.size(); i += 2) {
auto byte { hex.substr(i,2) };
str.push_back(std::strtol(byte.c_str(), nullptr, 16));
}
return str;
}
int main() {
std::string key_ {
R"(
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDd9VXmpHjV4voFO+0ZoFPlRr5icZXquxsr9EkaOUO9B7Wl1DAgGI0EKCm1++Bl2Od32xZFeFuG07OTpTMVOCPA==
-----END PUBLIC KEY-----
)"
};
std::string msg { decode_hex_str("562d6ddfb3ceb5abb12d97bc35c4963d249f55b7c75eda618d365492ee98d469") };
std::string sig { decode_hex_str("304502204d6d070117d445f4c2fcdbd4df037a1c8cfee2a166353c2e562cd5efd06e914d022100bb06439ded1478bd19022519dc06a84ba18ea4bf30ea9eb9ea90f8b66dad12c7") };
auto bio { BIO_new_mem_buf(key_.data(), key_.length()) };
assert(bio);
auto key { PEM_read_bio_EC_PUBKEY(bio, nullptr, nullptr, nullptr) };
EVP_MD_CTX *mdctx { nullptr };
EVP_PKEY *pkey { nullptr };
int status;
bool verified;
mdctx = EVP_MD_CTX_new();
assert(mdctx);
pkey = EVP_PKEY_new();
assert(pkey);
assert(EVP_PKEY_assign_EC_KEY(pkey, key) == 1);
assert(EVP_DigestVerifyInit(mdctx, nullptr, EVP_sha256(), nullptr, pkey) == 1);
assert(EVP_DigestVerifyUpdate(mdctx, msg.data(), msg.length()) == 1);
status = EVP_DigestVerifyFinal(mdctx, reinterpret_cast<unsigned char const *>(sig.data()), sig.length());
switch (status) {
case 0:
verified = false;
break;
case 1:
verified = true;
break;
default:
assert(false);
}
EVP_MD_CTX_free(mdctx);
EVP_PKEY_free(pkey);
assert(verified);
}
| EVP_DigestVerify{Init/Update/Final} do two things:
They hash the input data
Then they verify the computed hash against the signature
ecdsa.VerifyASN1 on the other hand does only the second step from the above, already taking in the hash as input.
The OpenSSL function that does that is ECDSA_verify.
So you can do something like:
BIO* bio = BIO_new_mem_buf(key_.data(), key_.length());
EC_KEY* key = PEM_read_bio_EC_PUBKEY(bio, nullptr, nullptr, nullptr);
int verified = ECDSA_verify(
0,
(unsigned char const*)msghash.data(), msghash.length(),
(unsigned char const*)sig.data(), sig.length(),
key
);
std::cout << verified << std::endl;
Should print 1.
Note that the variable naming in your code is confusing - the variable msg actually contains the message digest. So msghash or digest would be a better name for it. It is important to be precise in variable naming when doing crypto.
|
70,973,970 | 70,978,259 | cmake compile_commands.json for interface target | I have a simple c++ library that should be shipped as header-only library. The library depends on other libraries installed through CPM.
I'm using VS code and the compile_commands.json in order to notify VS code about the include paths from CPM packages. That does work as long as the project is configured as shared/static library or binary.
When using an INTERFACE target it however doesn't work anymore (compile_commands.json is generated but VS code shows include paths errors).
How do I use compile_commands.json with an interface target (header-only library) ?
The configuration below does work when defining binary target ( replacing INTERFACE with PUBLIC)!
CMakeLists.txt:
cmake_minimum_required(VERSION 3.21 FATAL_ERROR)
project(CpmCompileCommandsBug
LANGUAGES CXX
)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include(cmake/CPM.cmake)
CPMAddPackage(
NAME yaml-cpp
VERSION 0.6.3
GITHUB_REPOSITORY jbeder/yaml-cpp
GIT_TAG yaml-cpp-0.6.3
OPTIONS
"YAML_CPP_INSTALL ON"
)
add_library(${PROJECT_NAME} INTERFACE)
target_link_libraries(${PROJECT_NAME} INTERFACE yaml-cpp)
# the below target config does work
# add_library(${PROJECT_NAME} STATIC main.cpp)
# target_link_libraries(${PROJECT_NAME} PUBLIC yaml-cpp)
main.cpp:
#include <yaml-cpp/yaml.h>
| It turns out I was simply using the wrong target. Interfaces don't include any source files and thus won't generate any meaningful compile_commands.json.
What I was looking for is the object target which solves my issue completely.
Just for the reference, this is how the "correct" CMakeLists.txt would look like:
cmake_minimum_required(VERSION 3.21 FATAL_ERROR)
project(CpmCompileCommandsBug
LANGUAGES CXX
)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
include(cmake/CPM.cmake)
CPMAddPackage(
NAME yaml-cpp
VERSION 0.6.3
GITHUB_REPOSITORY jbeder/yaml-cpp
GIT_TAG yaml-cpp-0.6.3
OPTIONS
"YAML_CPP_INSTALL OFF"
)
# using OBJECT instead of INTERFACE allows passing source files
add_library(${PROJECT_NAME} OBJECT main.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC yaml-cpp)
|
70,974,463 | 70,974,659 | Returning the correct child type from a function | I have a UIComponent class. Window, Button and Text inherit from it. UIComponent has a recursive structure in that it stores a std::vector<std::unique_ptr<UIComponent>> contents;. I am trying to write a function that recursively that goes through contents and finds the given UIComponent.
In my original code, I use a hash-table, but the following code very closely resembles what the original looks like (sorry if it's a bit long – I couldn't make it any shorter):
#include <vector>
#include <string>
#include <memory>
#include <iostream>
class UIComponent
{
public:
std::string name = "";
UIComponent() = default;
std::vector<std::unique_ptr<UIComponent>> contents;
UIComponent(const UIComponent& other) noexcept
{
for (auto& otherContent : other.contents)
{
contents.push_back(
std::make_unique<UIComponent>(*otherContent)//recursive call
);
}
}
template <
template <class> class Component,
class Fx
>
void Attach(const Component<Fx>& comp, std::string name)
{
contents.push_back(
std::move(std::make_unique<Component<Fx>>(comp))
);
contents.back()->name = name;
}
//Should search all the components and return one that matches
//the argument
UIComponent* GetComponent(const std::string& name)
{
static UIComponent* pOut = nullptr;
for (size_t i = 0; i < contents.size(); i++)
{
if (name == contents[i]->name)
{
pOut = contents[i].get();
return pOut;
}
}
if (pOut != nullptr)
{
return pOut;
}
for (auto& content : contents)
{
content->GetComponent(name);
}
return pOut;
}
};
template < class Fx >
class Window : public UIComponent
{
public:
Window() = default;
};
template < class Fx >
class Button : public UIComponent
{
public:
Button() = default;
};
template < class Fx >
class Text : public UIComponent
{
public:
Text() = default;
};
Window<void(void)> window;
Button<void(void)> button;
Text<void(void)> text;
int main()
{
window.Attach<Button, void(void)>(button, "button");
button.Attach<Text, void(void)>(text, "text");
auto b = window.GetComponent("button");
if (b != nullptr)
{
std::cout << b->name << " : " << typeid(*b).name() << '\n';
}
auto t = window.GetComponent("text");
if (t != nullptr)
{
std::cout << t->name << " : " << typeid(*t).name() << '\n';
}
}
Actual Output:
button : class UIComponent
button : class UIComponent
Expected output:
button : class Button<void(void)>
text : Text<void(void)>
The function I am struggling with is UIComponent* GetComponent(const std::string& name).
It always returns a UIComponent*. I am not sure how to make it so that tt returns the correct child class type. I am also not sure about the logic but that might not be strictly related to the question.
| For the polymorphic behaviour you are attempting to work, you need at least one of the base class member functions to be virtual.
In your code, simply adding that specifier to the GetComponent member function will do the trick; like this:
virtual UIComponent* GetComponent(const std::string& name)
{
// ... all other code as in the original.
With this simple edit, the output I see when I run your code is then1:
button : class Button<void __cdecl(void)>
button : class Button<void __cdecl(void)>
So, although you'll then need to do some 'tidying up' of the returned class names, you will at least get pointers that reflect the actual run-time objects.
But note: as you now have a virtual member function, you really ought to also make the destructor(s) virtual, as well: When to use virtual destructors? So, add this to the base class definition:
virtual ~UIComponent() = default;
1 Edit: Note that, in your main function, there appears to be a conflict between the window and button objects, in terms of which one the "Text" control is attached to. The object in the Attach call and in the subsequent GetComponent call should be the same (they aren't in your original code). Here is an example of the main code edited so that they are the same, as follows:
int main()
{
window.Attach<Button, void(void)>(button, "button");
button.Attach<Text, void(void)>(text, "text"); // NOTE: You are attaching to the button ...
auto b = window.GetComponent("button");
if (b != nullptr) {
std::cout << b->name << " : " << typeid(*b).name() << '\n';
}
auto t = button.GetComponent("text"); // NOTE: Using "button.GetComponent"
if (t != nullptr) {
std::cout << t->name << " : " << typeid(*t).name() << '\n';
}
}
The output is now (as expected):
button : class Button<void __cdecl(void)>
text : class Text<void __cdecl(void)>
|
70,974,476 | 70,977,817 | Efficiently load/compute/pack 64 double comparison results in uint64_t bitmask | I want to load/compare/pack as runtime efficent as possible the results of 64 double comparisons into a uint64_t bitmask.
My current approach is to compare 2*2 pairs via AVX2 using _mm256_cmp_pd. The result of both (=8) comparisons is converted into a bitmap using _mm256_movemask_pd and via a|b<<4 assigned as byte into a union (1x uint64_t / 8 uint8_t) to save a few shifts/or's.
This example might help to visualize
union ui64 {
uint64_t i64;
struct { uint8_t i0,i1,i2,i3,i4,i5,i6,i7; } i8;
};
static inline uint64_t cmp64 (double* in0, double* in1) {
ui64 result;
// +0
result.i8.i0 =
_mm256_movemask_pd(
_mm256_cmp_pd(
_mm256_load_pd(in0 + 0),
_mm256_load_pd(in1 + 0),
_CMP_LT_OQ)) |
_mm256_movemask_pd(
_mm256_cmp_pd(
_mm256_load_pd(in0 + 4),
_mm256_load_pd(in1 + 4),
_CMP_LT_OQ)) << 4;
// +8
// load, compare, pack n+8 each 'iteration' using result.i8.i1,...i7
// ...
return result.i64;
}
Variants of compress&set appear straight forward, but use slower instructions: 1x _mm256_set_m128 and 2x_mm256_cvtpd_ps versus a scalar << and | like this
_mm256_movemask_ps(_mm256_set_m128(
_mm256_cvtpd_ps(v0),
_mm256_cvtpd_ps(v1)));
Used CPU is a Zen 1 (max AVX2), not sure if GPU usage(Nvidia) is an option.
Please share your thoughts.
| Here’s an example. It packs the comparison results into bytes with whatever instructions were the most efficient, shuffles into correct order once per 32 numbers, and uses _mm256_movemask_epi8 to produce 32 bits at once.
// Compare 4 numbers, return 32 bytes with results of 4 comparisons:
// 00000000 11111111 22222222 33333333
inline __m256d compare4( const double* a, const double* b )
{
return _mm256_cmp_pd( _mm256_load_pd( a ), _mm256_load_pd( b ), _CMP_LT_OQ );
}
// Compare 8 numbers, combine 8 results into the following bytes:
// 0000 4444 1111 5555 2222 6666 3333 7777
inline __m256i compare8( const double* a, const double* b )
{
__m256 c0 = _mm256_castpd_ps( compare4( a, b ) );
__m256 c1 = _mm256_castpd_ps( compare4( a + 4, b + 4 ) );
return _mm256_castps_si256( _mm256_blend_ps( c0, c1, 0b10101010 ) );
}
// Compare 16 numbers, combine 16 results into following bytes:
// 00 44 11 55 88 CC 99 DD 22 66 33 77 AA EE BB FF
inline __m256i compare16( const double* a, const double* b )
{
__m256i c0 = compare8( a, b );
__m256i c1 = compare8( a + 8, b + 8 );
return _mm256_packs_epi32( c0, c1 );
}
inline uint32_t compare32( const double* a, const double* b )
{
// Compare 32 numbers and merge them into a single vector
__m256i c0 = compare16( a, b );
__m256i c1 = compare16( a + 16, b + 16 );
__m256i src = _mm256_packs_epi16( c0, c1 );
// We got the 32 bytes, but the byte order is screwed up in that vector:
// 0 4 1 5 8 12 9 13 16 20 17 21 24 28 25 29
// 2 6 3 7 10 14 11 15 18 22 19 23 26 30 27 31
// The following 2 instructions are fixing the order
// Shuffle 8-byte pieces across the complete vector
// That instruction is relatively expensive on most CPUs, but we only doing it once per 32 numbers
src = _mm256_permute4x64_epi64( src, _MM_SHUFFLE( 3, 1, 2, 0 ) );
// The order of bytes in the vector is still wrong:
// 0 4 1 5 8 12 9 13 2 6 3 7 10 14 11 15
// 13 16 20 17 21 24 28 25 18 22 19 23 26 30 27 31
// Need one more shuffle instruction
const __m128i perm16 = _mm_setr_epi8(
0, 2, 8, 10, 1, 3, 9, 11, 4, 6, 12, 14, 5, 7, 13, 15 );
// If you calling this in a loop and everything is inlined,
// the shuffling vector should be pre-loaded outside of the loop.
const __m256i perm = _mm256_broadcastsi128_si256( perm16 );
// Shuffle the bytes
src = _mm256_shuffle_epi8( src, perm );
// The order of bytes is now correct, can use _mm256_movemask_epi8 to make 32 bits of the result
return (uint32_t)_mm256_movemask_epi8( src );
}
uint64_t compareAndPack64( const double* a, const double* b )
{
uint64_t low = compare32( a, b );
uint64_t high = compare32( a + 32, b + 32 );
return low | ( high << 32 );
}
|
70,974,613 | 71,031,583 | Is there a way to detect if a given header of the C++ Standard Library is included? | More specifically, is it possible to detect, at compilation time, if a C++ standard header file is included (let say <complex>), and do that in a way that is cross-plateform and cross-compiler ? I'd like it to work with C++11 at least, but for the question's sake, is it possible for any C++ standard ?
I know the implementation of the C++ Standard Library is dependent on the compiler and operating system, but is there a standardized guard name for the header, a macro that I can check the existence of ?
I've run into this : Detect usage of STL in C++ , which is a hack not to use the headers, and this : Is there a way to detect portably that a standard header is included using macros?, which answers with a C++17 feature, and is in fact more about detecting a function.
What I want is to be able to write some preprocessor instruction at a given point in the code that will tell whether the header is included (yet). I checked the source code of (an implementation of) <complex> as an example, and _GLIBCXX_COMPLEX is defined, but probably only for this implementation.
| TL;DR : No, there is not, apart from the C++17 feature #if __has_include(<complex>). Not with defined macro anyway.
Long answer : there are two parts to the answer. What I read from some headers, and the tests I ran on differents OS with differents compilers.
Warning : I will write also about C, as some compilers uses the same macros. I also use the shortcut 'for C' and 'for C++' instead of 'when the header complex.h is included' and 'when the header <complex> is included'.
Ok, here's my best answer as for now.
About C and complex.h :
In C, the existence of the macro
_Complex_I is the only macro that I think should be defined in any complex.h header, as it is specified by the ISO C99 (cf. ISO/IEC 9899:1999/TC3 text). The tests I ran shows that this is a realistic hypothesis. There are some additionnal macro used, such as _COMPLEX_H that seems to be defined when compiling with GCC,
and _C_COMPLEX_T when compiling with MSVC. There might be others, I didn't find them, please don't hesitate to add them.
But it is C, not C++, and one should not mix both.
About C++ and <complex> :
The C++ standard (ISO/CEI 14882:2011) does not specify such macro. In fact, it does not specify the inclusion of any macro (at first glance).
It does specify the existence of the complex class however, but this does not answer the question.
For what I read, _COMPLEX_ and _C_COMPLEX_T seems to be defined in the <complex> header for
LLVM-clang and MSVC, but also in the complex.h for the apple implementation of the C math library (libm).
However, my tests with the LLVM-clang compiler on macOS failed showing those macro, and I can't find the file where I read that information.
I also found that g++ is defining _GLIBCXX_COMPLEX.
If one wanted to do that with a C++ older than C++17, a solution would be to test with the given compilers and architectures the code will run onto.
That is quite bad, but it's the closest answer I get.
The tests :
I give here the code that I run on the different OS, the compiler options, their version, and the results they prompt. _Complex_I was indeed defined for all C headers.
I wasn't able to run the test on macOS with GCC and G++, but I bet that _Complex_I will be defined with GCC and _GLIBCXX_COMPLEX with G++.
Tests for C++
G++ -std=c++11 v9.3.0 on Ubuntu 20.04 :
_GLIBCXX_COMPLEX
G++ -std=c++11 v11.2.0 on windows 10 (via Cygwin) :
_GLIBCXX_COMPLEX
MSVC default c++11 option v14.29.xxxxx.x on windows 10 :
_C_COMPLEX_T
_COMPLEX_
Apple LLVM-clang -std=c++11 v10.0.1 : None (doesn't mean there is none, just that I don't know which one)
Code for C++:
#include <iostream>
#include <complex>
int main(){
#ifdef _COMPLEX_
std::cout << "_COMPLEX_" << std::endl;
#endif
#ifdef _C_COMPLEX_T
std::cout << "_C_COMPLEX_T" << std::endl;
#endif
#ifdef _COMPLEX_H
std::cout << "_COMPLEX_H" << std::endl;
#endif
#ifdef _Complex_I
std::cout << "_Complex_I" << std::endl;
#endif
#ifdef _GLIBCXX_COMPLEX
std::cout << "_GLIBCXX_COMPLEX" << std::endl;
#endif
return 0;
}
Tests for C :
GCC -std=c99 v9.3.0 on Ubuntu 20.04 :
_Complex_I _COMPLEX_H
GCC -std=c99 v11.2.0 on windows 10 (via Cygwin) :
_Complex_I _COMPLEX_H
MSVC -std=c99 v14.29.xxxxx.x on windows 10 :
_Complex_I _C_COMPLEX_T
Apple LLVM-clang -std=c99 v10.0.1 : _Complex_I
Code for C:
#include <stdlib.h>
#include <stdio.h>
#include <complex.h>
int main(){
#ifdef _COMPLEX_
printf("_COMPLEX_\n");
#endif
#ifdef _C_COMPLEX_T
printf("_C_COMPLEX_T\n");
#endif
#ifdef _COMPLEX_H
printf("_COMPLEX_H\n");
#endif
#ifdef _Complex_I
printf("_Complex_I\n");
#endif
#ifdef _GLIBCXX_COMPLEX
printf("_GLIBCXX_COMPLEX\n");
#endif
return 0;
}
To sum up :
MSVC is defining _C_COMPLEX_T whatever C or C++ used, and also _COMPLEX_ for C++. _Complex_I is always defined for C, and G++ seems to define _GLIBCXX_COMPLEX whatever the plateform (test to be done on macOS) for C++.
|
70,975,375 | 71,377,680 | xcb correct window size | I have a question regarding xcb Window size
I create a window using xcb_create_window function
xcb_create_window(mScreen->connection(),
XCB_COPY_FROM_PARENT,
mWindow,
mScreen->screen()->root,
x, // left corner of the window client area
y, // upper corner of the window client area
width, // width of the client area
height, // height of the client area
0,
XCB_WINDOW_CLASS_INPUT_OUTPUT,
mScreen->screen()->root_visual,
value_mask,
value_list);
auto reply = XCB_REPLY(xcb_intern_atom, mScreen->connection(), true, strlen("WM_PROTOCOLS"), "WM_PROTOCOLS");
auto atomDelete = XCB_REPLY(xcb_intern_atom, mScreen->connection(), false, strlen("WM_DELETE_WINDOW"), "WM_DELETE_WINDOW");
xcb_change_property(mScreen->connection(), XCB_PROP_MODE_REPLACE, mWindow, reply->atom, 4, 32, 1, &atomDelete->atom);
xcb_change_property(mScreen->connection(), XCB_PROP_MODE_REPLACE, mWindow, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8, strlen(windowName), windowName);
xcb_flush(mScreen->connection());
On Win32 API I have the possibilty to adjust a window rect by using AdjustWindowRect function which basically adds border and caption size to ensure client window does have the expected size.
My question how do I achieve this with xcb? Is there any way to compute the additonal size that is needed to ensure client window das have the expected size?
| The following code gets margins of a window
followed suggestion from Erdal Küçük:
create window
configure stuff (like title or close button)
wait for property message
in case _NET_FRAME_EXTENTS read data
uint32_t value_mask, value_list[32]{};
auto windowHandle = xcb_generate_id(xcb_connection());
value_mask = XCB_CW_EVENT_MASK;
value_list[0] = XCB_EVENT_MASK_PROPERTY_CHANGE;
xcb_create_window(screen->connection(),
XCB_COPY_FROM_PARENT,
windowHandle,
screen->root,
100,
100,
100,
100,
0,
XCB_WINDOW_CLASS_INPUT_OUTPUT,
screen->root_visual,
value_mask,
value_list);
auto protocols = XCB_REPLY(xcb_intern_atom, screen->connection(), true, strlen("WM_PROTOCOLS"), "WM_PROTOCOLS");
auto atomDelete = XCB_REPLY(xcb_intern_atom, screen->connection(), false, strlen("WM_DELETE_WINDOW"), "WM_DELETE_WINDOW");
auto atomExtents = XCB_REPLY(xcb_intern_atom, screen->connection(), false, strlen("_NET_FRAME_EXTENTS"), "_NET_FRAME_EXTENTS");
xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, windowHandle, protocols->atom, XCB_ATOM_ATOM, 32, 1, &atomDelete->atom);
xcb_change_property(xcb_connection(), XCB_PROP_MODE_REPLACE, windowHandle, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8, strlen(""), "");
xcb_map_window(xcb_connection(), windowHandle);
xcb_flush(xcb_connection());
xcb_generic_event_t* event;
for (;;) {
while ((event = xcb_poll_for_event(screen->connection()))) {
switch (event->response_type & 0x7f) {
case XCB_PROPERTY_NOTIFY: {
auto propertyNotify = (const xcb_property_notify_event_t*)event;
if (propertyNotify->atom == atomExtents->atom) {
free(event);
goto end;
}
break;
}
default:
break;
}
free(event);
}
}
end:
auto extends = XCB_REPLY(xcb_get_property, xcb_connection(), false, windowHandle, atomExtents->atom, XCB_ATOM_CARDINAL, 0, 4);
if (extends && extends->type == XCB_ATOM_CARDINAL && extends->format == 32 && extends->value_len == 4) {
uint32_t* data = std::pointer_cast<uint32_t*>(xcb_get_property_value(extends.get()));
windowMargins.l = -data[0];
windowMargins.r = data[1];
windowMargins.t = -data[2];
windowMargins.b = data[3];
}
xcb_destroy_window(xcb_connection(), windowHandle);
|
70,975,403 | 70,975,456 | How to write a generic function to print begin and end iterator elements | The function below, printloop, is able to print the elements in a collection as below. But if I try to remove the loop and use std::copy, how do I get that version, print, to work?
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
// this print function doesn't compile
template <typename iter>
void print(iter begin, iter end) {
std::copy(begin, end,
std::ostream_iterator< what type? >(std::cout, "\t"));
}
template <typename iter>
void printloop(iter begin, iter end) {
while (begin != end) {
std::cout << *begin << '\t';
begin++;
}
}
int main() {
std::vector<int> vec {1,2,3,4,5};
printloop(vec.begin(), vec.end()); // works ok
print(vec.begin(), vec.end()); // how to get working?
}
| You might use iterator_traits:
template <typename iter>
void print(iter begin, iter end) {
using value_type = typename std::iterator_traits<iter>::value_type;
std::copy(begin, end, std::ostream_iterator<value_type >(std::cout, "\t"));
}
Demo
|
70,975,663 | 70,975,730 | Can I initialize a std::array<uint8_t with a string literal? | I write a lot of C code interacting with instruments using UART serial ports. I'm starting a new project where I'm trying to use a more object oriented approach with C++. Here's how I've defined and sent commands in the past using C.
uint8_t pubx04Cmd[] = "$PUBX,04*37\r\n";
HAL_UART_Transmit(&hUART1, pubx04Cmd, sizeof(pubx04Cmd), 5000);
Which is pretty darn simple. C++ std::arrays have the size built in which seems kind of useful. But here's the only way I've figured out how to do it.
const char pubx04CString[] = "$PUBX,04*37\r\n";
std::array<uint8_t, 14> pubx04CPPArray;
std::copy(std::begin(pubx04CString), std::end(pubx04CString), pubx04CPPArray.begin());
HAL_UART_Transmit(&hUART1, pubx04CPPArray.data(), pubx04CPPArray.size(), 5000);
Which seems pretty clunky compared to the C way to do it.
Is there a cleaner way to do this using std::array?
Is there any real benefit to using std::arrays vs C arrays for this situation?
| std::array is an aggregate, i.e. a possible implementation may be like
template <typename T, size_t S>
struct array {
T a[S];
// ...
};
The enclosed array can be initializes as usual:
std::array<uint8_t, 14> pubx04Cmd{"$PUBX,04*37\r\n"};
|
70,975,761 | 70,976,110 | MSVC: C++14: std:set: comparison function: why "const" is required? | Sample code:
#include <string>
#include <set>
using namespace std;
class x
{
private:
int i;
public:
int get_i() const { return i; }
};
struct x_cmp
{
bool operator()(x const & m1, x const & m2)
#if _MSC_VER
const
#endif
{
return m1.get_i() > m2.get_i();
}
};
std::set<x, x_cmp> members;
void add_member(x const & member)
{
members.insert(member);
}
Invocations:
$ g++ -c -std=c++14 -pedantic -Wall -Wextra
<nothing>
$ clang++ -c -std=c++14 -pedantic -Wall -Wextra
<nothing>
$ icc -c -std=c++14 -pedantic -Wall -Wextra
<nothing>
$ cl /c /std:c++14 /Za
<nothing>
Question: why msvc requires const while others don't? Or why others don't require const?
| This is LWG2542. In C++14, the wording for the comparison operator said "possibly const", which was interpreted by GCC and Clang as meaning that the comparison operator was not required to be const qualified. MSVC always required it.
This is a wording defect, as comparison operators for associative containers should be const qualified. This was changed in C++17 to require the comparator to be const. This is a breaking change, so valid (though broken) C++14 code may fail to compile in C++17.
|
70,976,288 | 70,976,344 | The value of integer is changing without any calculation | I have no idea why suddenly the value of integer is changing even though there's no process of caluclation, here's the code of my program :
#include <iostream>
using namespace std;
int main()
{
int n;
int a[] = {};
int b[] = {};
cin >> n;
cout << "\n";
for(int i=0;i<n;i++)
cin >> a[i];
cout << "\n";
for(int i=0;i<n;i++)
cin >> b[i];
cout << "\n";
for(int i=0;i<n;i++)
cout << a[i] << " " << b[i] << "\n";
cout << n;
}
So if I input the value of n lower than 5, there's no problem with the code. But if I put the value of n higher than 4, the value of integer a[i] will follow the value of b[i] somehow and the value of n is different from what I input.
As for example it's like this
Input :
10
1
2
3
4
5
6
7
8
91
92
93
94
95
96
97
98
Output :
95 91
96 92
97 93
98 94
5 95
6 96
7 97
8 98
8
As you can see the value of n changing from 10 to 8, and the loop only happen for 8 times. Why the value of n and a[i] are changing? Any help is appreciated, thanks
| These declarations
int a[] = {};
int b[] = {};
invoke undefined behavior because you may not declare arrays with the number of elements equal to 0.
It seems you are trying to use variable length arrays that is not a standard C++ feature.
Nevertheless if the compiler supports this feature then you need at least to write
int n;
cin >> n;
cout << "\n";
int a[n];
int b[n];
for(int i=0;i<n;i++)
cin >> a[i];
That is you may declare the arrays after the variable n will have a positive value.
But it is much better not to use non-standard language extensions. So instead of the variable length arrays you should use the standard container std::vector<int>.
|
70,976,291 | 70,976,366 | libc++abi: terminating with uncaught exception of type std::length_error: basic_string | I'm trying to read a .CSV file and I'm encountering errors with reading strings.
For context, this .CSV file contains a person's name followed by a few personality traits (e.g., likes cats, chocolate, mountains, etc.). I want to read in this data and store it in a map<string, vector<string> > where the person's name is the key and the value is a vector with each personality trait in it.
I'm using the following code, but the moment I uncomment the line stringstream s(line);, I get this error:
libc++abi: terminating with uncaught exception of type std::length_error: basic_string
Could anyone tell me what this error means, why I'm getting it, and how to avoid getting it in the future? Any help is appreciated c:
P.S. I've also included the rest of the function commented out so you can see what the finished product is supposed to do. Here's some sample data that I made up:
John,Dog,DC,Beach,Hamburgers,Brownies
Sue,Cat,DC,Beach,Hot Dogs,Brownies
Jim,Dog,Marvel,Mountains,Hot Dogs,Cupcakes
and it should get stored as:
[John] = {Dog, DC, Beach, Hamburgers, Brownies}
[Sue] = {Cat, DC, Beach, Hot Dogs, Brownies}
[Jim] = {Dog, Marvel, Mountains, Hot Dogs, Cupcakes}
//specialized function for reading files
//stores the values in the file in a map with the participant's name as the key and a vector of
//strings as the value
map<string, vector<string> > readFile(fstream & f) {
map<string, vector<string> > output;
//variables for use in splitting the values stored in the .csv
vector<string> row;
string word, line;
//reading the file
while (!f.eof()) {
row.clear();
//reading the next line in the file
getline(f, line);
//removing the trailing newline character
line.pop_back();
//creating new string stream object using line
//stringstream s(line);
/*
//separating the contents of a line by commas and storing them in row
while (getline(s, word, ',')) {
row.push_back(word);
}
//removing the name from the beginning of the vector and storing it in a
//separate variable
string name = row[0];
row.erase(row.begin());
//adding new entry to output
output[name] = row;
*/
}
return output;
}
| The problem here is that f.eof() won't return true until getline fails. When getline reads the last line in the file, the getline succeeds, the file is positioned after the last byte, but f.eof is not yet set. Thus, you are calling line.pop_back() on a zero-length string.
Instead, use this idiom:
while( getline(f, line) )
{
row.clear()
...
|
70,976,393 | 70,998,967 | Add a cv::Mat inside a cv::Mat at a specific position | I am currently making a soft that renders chess game. To do it, I use OpenCV.
The idea is to have the chess board in a cv::Mat and add pieces with a std::array of cv::Mat :
RenderImage::RenderImage() {
backgroundChess = cv::imread("files/board_chess4.png"); /// The chess board
piecesChess[0] = cv::imread("files/pieces/wP.png"); /// The pieces
piecesChess[1] = cv::imread("files/pieces/wB.png");
piecesChess[2] = cv::imread("files/pieces/wN.png");
piecesChess[3] = cv::imread("files/pieces/wR.png");
piecesChess[4] = cv::imread("files/pieces/wQ.png");
piecesChess[5] = cv::imread("files/pieces/wK.png");
piecesChess[6] = cv::imread("files/pieces/bP.png");
piecesChess[7] = cv::imread("files/pieces/bB.png");
piecesChess[8] = cv::imread("files/pieces/bN.png");
piecesChess[9] = cv::imread("files/pieces/bR.png");
piecesChess[10] = cv::imread("files/pieces/bQ.png");
piecesChess[11] = cv::imread("files/pieces/bK.png");
}
And after, I have made a method to try to add a piece in the chess board.
I have started by use the copyTo:
cv::Mat RenderImage::getImage() {
cv::Mat chess = backgroundChess.clone();
piecesChess[0].copyTo(chess(cv::Rect(0,0, piecesChess[0].cols, piecesChess[0].rows)));
cv::imshow("Display Image", chess);
cv::waitKey(0);
return chess;
}
But I have a black square like around the piece:
So I tryed to make my own methods:
void RenderImage::merge2img(cv::Mat& back, const cv::Mat front, std::size_t posX, std::size_t posY) {
cv::Size bsize { back.size() };
cv::Size fsize { front.size() };
for (std::size_t startX {posX}; startX < posX + fsize.width && startX < bsize.width; startX++) {
for (std::size_t startY {posY}; startY < posY + fsize.height && startY < bsize.height; startY++) {
cv::Vec4b fpixel { front.at<cv::Vec4b>(startY, startX) };
cv::Vec4b bpixel { back.at<cv::Vec4b>(startY, startX) };
for (int i {0}; i < 3; i++) {
back.at<cv::Vec4b>(startY, startX)[i] = (fpixel[i] * fpixel[3] + bpixel[i] * (255 - fpixel[3])) / 255;
}
back.at<cv::Vec4b>(startY, startX)[3] = 255;
}
}
}
And I have changed the methode getImage()
cv::Mat RenderImage::getImage() {
cv::Mat chess = backgroundChess.clone();
//addWeighted( piecesChess[0], 0.5, backgroundChess, 0.5, 0.0, chess);
merge2img(chess, piecesChess[0], 0, 0);
//piecesChess[0].copyTo(chess(cv::Rect(0,0, piecesChess[0].cols, piecesChess[0].rows)));
cv::imshow("Display Image", chess);
//cv::imshow("Display Image", piecesChess[0]);
cv::waitKey(0);
return chess;
}
But the result have this problem :
So can you help me to find a solution to draw piece inside my chess board ?
Thank you
| Thanks you @Christoph Rackwitz, with your link I have found the solution.
I convert the python code of Try2Code ( enter link description here )
The final code is here :
void RenderImage::overlayImage(cv::Mat& back, const cv::Mat& front, std::size_t posX, std::size_t posY) {
cv::Mat gray, mask, mask_inv, back_bg, front_bg, result;
cv::Size fsize { front.size() };
cv::cvtColor(front, gray, cv::COLOR_BGR2GRAY);
cv::threshold(gray, mask, 0, 255, cv::THRESH_BINARY);
cv::bitwise_not(mask, mask_inv);
cv::Mat roi { back(cv::Range(posX, posX + fsize.width), cv::Range(posY, fsize.height)) };
cv::bitwise_and(roi, roi, back_bg, mask_inv);
cv::bitwise_and(front, front, front_bg, mask);
cv::add(back_bg, front_bg, result);
cv::addWeighted(roi, 0.1, result, 0.9, 0.0, result);
result.copyTo(back(cv::Rect(posX, posY, fsize.width, fsize.height)));
}
cv::Mat RenderImage::getImage() {
cv::Mat chess = backgroundChess.clone();
overlayImage(chess, piecesChess[0], 128, 0); //The method to merge two images
cv::imshow("Display Image", chess);
cv::waitKey(0);
return chess;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.