question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
71,979,469 | 71,979,876 | How to use cmath functions like div in C++? | I am new to C++ and I am not sure how to use some of the cmath functions like div.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
if (n < 10) {
cout << div(n , 2);
}
return 0;
}
| The reason cout << div(n , 2) doesn't work is because div doesn't return a number, instead div returns a struct with 2 values in there, quot and rem.
So when you use div(10, 3), it will returns a object with .quot == 3 and .rem == 1.
To print the result of div, you would need to first store the result, then print each members separately:
auto result = std::div(10, 3);
std::cout << "Quot: " << result.quot << '\n';
std::cout << "Rem: " << result.rem << '\n';
|
71,979,526 | 71,979,820 | How can I calculate the tens place value of 2^100 in C++? | How can I calculate the tens place value of 2^100 in C++?
I tried this;
#include <cmath>
#include <iostream>
using namespace std;
int main(){
int answer;
answer = (unsigned long long int)pow(2, 100) % 100 / 10; //zero
cout << answer << endl;
return 0;
}
But it printed 0 because of overflow.
Python prints the answer correctly with this code;
print(2 ** 100 % 100 // 10)
But how do I calculate it in C++?
| You have a problem with typecasting.
As you can see from documentation std::pow return double
So first step to solve our problem, try to remove type casting.
std::pow(2, 100); // return 1.26765e+30
The next problem we can't use operator % with double type so we need std::fmod
So final solution would look like this:
int answer = std::fmod(std::pow(2, 100), 100) / 10;
|
71,979,628 | 71,979,978 | How can I output bit pattern of infinity and NaN in C++?(IEEE standard) | I'm reading Computer Systems: A Programmer’s Perspective, then I found the Special Values's definition and corresponding bit patterns.
Now, I wanna output their bits using C++. I use their macro to output bits, obviously is incorrect, because macro defined to Integer!
#define FP_NAN 0x0100
#define FP_NORMAL 0x0400
#define FP_INFINITE (FP_NAN | FP_NORMAL)
What should I do to correctly output bits in the image above? and, Why compiler defined those Integer macros rather than IEEE standard?
below is my code.
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
union U {
float f;
int i;
};
int main() {
U u1, u2;
u1.f = FP_NAN;
u2.f = FP_INFINITE;
cout << bitset<32>(u1.i) << endl;
cout << bitset<32>(u2.i) << endl;
return 0;
}
output:
01000011100000000000000000000000
01000100101000000000000000000000
My computer environment:
win10
mingw64
| I wrote a quick-and-dirty double bit-wise output program a while back. You could modify it to work for float.
It has ANSI escape sequences in it, which might not be suitable for your environment.
The key part is just using a byte memory pointer and examining the bit state directly, rather than trying to get std::bitset to play nice.
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
using std::cout;
using std::fpclassify;
using std::memcpy;
using std::nan;
using std::numeric_limits;
using std::reverse;
using std::setw;
using std::size_t;
using std::string;
using std::stringstream;
using std::uint32_t;
using std::uint64_t;
namespace {
uint32_t low32_from(double d) {
char const* p = reinterpret_cast<char const*>(&d);
uint32_t result;
memcpy(&result, p, sizeof result);
return result;
}
uint32_t high32_from(double d) {
char const* p = reinterpret_cast<char const*>(&d);
p += 4;
uint32_t result;
memcpy(&result, p, sizeof result);
return result;
}
string hexstr(uint32_t value) {
char hex[] = "0123456789ABCDEF";
unsigned char buffer[4];
memcpy(buffer, &value, sizeof buffer);
auto p = &buffer[0];
stringstream ss;
char const* sep = "";
for (size_t i = 0; i < sizeof buffer; ++i) {
ss << sep << hex[(*p >> 4) & 0xF] << hex[*p & 0xF];
sep = " ";
++p;
}
return ss.str();
}
string bits(uint64_t v, size_t len) {
string s;
int group = 0;
while (len--) {
if (group == 4) { s.push_back('\''); group = 0; }
s.push_back(v & 1 ? '1' : '0');
v >>= 1;
++group;
}
reverse(s.begin(), s.end());
return s;
}
string doublebits(double d) {
auto dx = fpclassify(d);
unsigned char buffer[8];
memcpy(buffer, &d, sizeof buffer);
stringstream ss;
uint64_t s = (buffer[7] >> 7) & 0x1;
uint64_t e = ((buffer[7] & 0x7FU) << 4) | ((buffer[6] >> 4) & 0xFU);
uint64_t f = buffer[6] & 0xFU;
f = (f << 8) + (buffer[5] & 0xFFU);
f = (f << 8) + (buffer[4] & 0xFFU);
f = (f << 8) + (buffer[3] & 0xFFU);
f = (f << 8) + (buffer[2] & 0xFFU);
f = (f << 8) + (buffer[1] & 0xFFU);
f = (f << 8) + (buffer[0] & 0xFFU);
ss << "sign:\033[0;32m" << bits(s, 1) << "\033[0m ";
if (s) ss << "(-) ";
else ss << "(+) ";
ss << "exp:\033[0;33m" << bits(e, 11) << "\033[0m ";
ss << "(" << setw(5) << (static_cast<int>(e) - 1023) << ") ";
ss << "frac:";
// 'i' for implied 1 bit, '.' for not applicable (so things align correctly).
if (dx == FP_NORMAL) ss << "\033[0;34mi";
else ss << "\033[0;37m.\033[34m";
ss << bits(f, 52) << "\033[0m";
if (dx == FP_INFINITE) ss << " \033[35mInfinite\033[0m";
else if (dx == FP_NAN) ss << " \033[35mNot-A-Number\033[0m";
else if (dx == FP_NORMAL) ss << " \033[35mNormal\033[0m";
else if (dx == FP_SUBNORMAL) ss << " \033[35mDenormalized\033[0m";
else if (dx == FP_ZERO) ss << " \033[35mZero\033[0m";
ss << " " << d;
return ss.str();
}
} // anon
int main() {
auto lo = low32_from(1111.2222);
auto hi = high32_from(1111.2222);
cout << hexstr(lo) << "\n";
cout << hexstr(hi) << "\n";
cout << doublebits(1111.2222) << "\n";
cout << doublebits(1.0) << "\n";
cout << doublebits(-1.0) << "\n";
cout << doublebits(+0.0) << "\n";
cout << doublebits(-0.0) << "\n";
cout << doublebits(numeric_limits<double>::infinity()) << "\n";
cout << doublebits(-numeric_limits<double>::infinity()) << "\n";
cout << doublebits(nan("")) << "\n";
double x = 1.0;
while (x > 0.0) {
cout << doublebits(x) << "\n";
x = x / 2.0;
}
}
|
71,979,970 | 73,921,436 | Constant evaluation of self-assignment in member initialization | In the following program, constexpr function foo() makes an object of A with the field x=1, then constructs another object on top of it using std::construct_at and default initialization x=x, then the constant evaluated value is printed:
#include <memory>
#include <iostream>
struct A {
int x = x;
};
constexpr int foo() {
A a{1};
std::construct_at<A>(&a);
return a.x;
}
constexpr int v = foo();
int main() {
std::cout << v;
}
GCC prints 1 here. Both Clang and MSVC print 0. And only Clang issues a warning: field 'x' is uninitialized when used. Demo: https://gcc.godbolt.org/z/WTsxdrj8e
Is there an undefined behavior in the program? If yes, why does no compiler detect it during constant evaluation? If no, which compiler is right?
| C++20 [basic.life]/1.5 states that the lifetime of an object (in this case, the object a) ends when
the storage which the object occupies is released, or is reused by an object that is not nested within o (6.7.2).
The standard isn't totally clear about when exactly the memory is considered "reused" (and thus, the old A's lifetime ends) but [intro.object]/1 states that
... An object occupies a region of storage in its period of construction (11.10.5), throughout its lifetime (6.7.3), and in its period of destruction (11.10.5).
In my opinion, the evaluation of the default member initializer = x is something that happens during the "period of construction" of the new A object, and that means that at that point, the new A object has already come into existence (but its lifetime has not yet begun), and the old object's lifetime has already ended. That means the initialization of the new A reads the value of its x member, whose lifetime has not begun because its initialization is not complete, which violates [basic.life]/7.1 and would be UB.
In C++20, the definition of foo violates [dcl.constexpr]/6:
A constexpr function that is neither defaulted nor a template is ill-formed, no diagnostic required, if it is not possible for an evaluation of an invocation of the function to be performed while evaluating any valid manifestly constant-evaluated expression.
This means compilers are not required to issue a diagnostic for your program.
In C++23, this rule will be abolished (see P2448) so you can argue that compilers must issue a diagnostic if they claim C++23 compliance. However, no compiler has ever been able to diagnose all kinds of core language UB in constant expressions (for example, something that seems particularly difficult to diagnose is unsequenced writes or an unsequenced read and write involving the same scalar object) so don't hold your breath for it to be fixed.
|
71,980,007 | 71,980,068 | Take value out of std::optional | How do you actually take a value out of optional? Meaning take ownership of the value inside the std::optional and replace it with std::nullopt (or swap it with another value)?
In Rust for example you could .unwrap your Option or do something like foo.take().unwrap(). I'm trying to do something like that with C++ optionals.
| operator*/value() returns a reference to the value held by the optional, so you can simply use std::move to move it to a temporary variable
std::optional<std::string> opt = "abc";
// "take" the contained value by calling operator* on a rvalue to optional
auto taken = *std::move(opt);
This will invoke the rvalue reference overload of operator*() of the optional, which returns an rvalue reference to the contained value.
You can also directly perform std::move on the return value of the operator*() of the lvalue optional, which will convert the lvalue reference of the contained value into an rvalue
auto taken = std::move(*opt);
|
71,980,108 | 71,980,166 | C++ 20 lambda in template: unable to deduce ‘auto*’ from lambda | Given the following simple wrapper struct (inspired by this answer):
template <auto* F> struct Wrapper;
template <class Ret, class... Args, auto (*F)(Args...) -> Ret>
struct Wrapper<F>
{
auto operator()(Args... args) const
{
return F(args...);
}
};
The following works:
int this_works(){
return 42;
}
int main(){
return Wrapper<this_works>()();
}
But I want this, using c++ 20:
int main(){
return Wrapper<[](){return 42;}>()();
}
g++-11 --std=c++20 and clang++13 --std=c++20 both complain about the latter
with some hard to decipher error messages, including:
mismatched types ‘auto*’ and ‘main()::<lambda()>
error: non-type template parameter 'F' with type 'auto *' has incompatible initializer
Is there a way to make the second example work? I tried a constexpr function
pointer to the lambda but it complained about it having no linkage ...
| Wrapper expects function pointer, but template argument deduction won't consider implicit conversion (from lambda without capture to function pointer).
You can convert the lambda to function pointer explicitly:
int main(){
return Wrapper<static_cast<int(*)()>([](){return 42;})>()();
}
or
int main(){
return Wrapper<+[](){return 42;}>()();
}
LIVE
|
71,980,406 | 71,981,318 | Compile-time efficient n-ary cartesian product of parameter packs with a transformation | In a previous question, solutions were given on how to compute the n-ary cartesian product of parameter packs (see here, here (and here but for tuples)). Basically, we consider the following wrapper:
template <class... Types>
struct pack {};
template <class... Packs>
struct pack_product {/* SOMETHING */}
template <class... Packs>
using pack_product_t = typename pack_product<Packs...>::type;
such that pack_product_t<pack<A0, A1>, pack<B0, B1, B2>, pack<C0, C1>> produces the following:
pack<
pack<A0, B0, C0>, pack<A0, B0, C1>,
pack<A0, B1, C0>, pack<A0, B1, C1>,
pack<A0, B2, C0>, pack<A0, B2, C1>,
pack<A1, B0, C0>, pack<A1, B0, C1>,
pack<A1, B1, C0>, pack<A1, B1, C1>,
pack<A1, B2, C0>, pack<A1, B2, C1>,
>;
(again see here and here for solutions, even if I think they do not fully work when one of the input packs is the empty pack pack<>). This corresponds to the n-ary cartesian product of sets A×B×C={(a0, b0, c0), ..., (a1, b2, c1)} (set of tuples from a set-theoretic standpoint).
As an important note, one of the tricky part was to produce just two levels of packs, and not n-nested packs in the result (as in pack<pack<pack<A0, B0>, C0>>, ...>).
Now, what I would like to do is the combination of the n-ary cartesian product:
template <template <class> class Function, class... Packs>
struct pack_product_apply {
using type = /* SOMETHING */
};
template <template <class> class Function, class... Packs>
using pack_product_apply_t = typename pack_product_apply<Function, Packs...>::type;
which basically computes:
pack<
typename Function<pack<A0, B0, C0>>::type, typename Function<pack<A0, B0, C1>>::type,
typename Function<pack<A0, B1, C0>>::type, typename Function<pack<A0, B1, C1>>::type,
typename Function<pack<A0, B2, C0>>::type, typename Function<pack<A0, B2, C1>>::type,
typename Function<pack<A1, B0, C0>>::type, typename Function<pack<A1, B0, C1>>::type,
typename Function<pack<A1, B1, C0>>::type, typename Function<pack<A1, B1, C1>>::type,
typename Function<pack<A1, B2, C0>>::type, typename Function<pack<A1, B2, C1>>::type,
>;
and just skips the elements which do not compile thanks to SFINAE: for example if the versions with B1 do not provide a valid ::type the result would just be:
pack<
typename Function<pack<A0, B0, C0>>::type, typename Function<pack<A0, B0, C1>>::type,
typename Function<pack<A0, B2, C0>>::type, typename Function<pack<A0, B2, C1>>::type,
typename Function<pack<A1, B0, C0>>::type, typename Function<pack<A1, B0, C1>>::type,
typename Function<pack<A1, B2, C0>>::type, typename Function<pack<A1, B2, C1>>::type,
>;
And example of input type function would be:
template <class Pack>
struct my_type_function;
template <class... Types>
struct my_type_function<pack<Types...>>: std::common_type<Types...> {};
Computing the cartesian product first and applying the function after on its result is a no-brainer. But I have the feeling (but I may be wrong) that it would be suboptimal from the compiler standpoint.
QUESTION: How to implement pack_product_apply in a compiler-efficient way where the type function would be applied "on-the-fly" when computing each element of the product instead of computing all the element first and then applying the function?
| This works with O(1) instantiation depth
template<template<typename...> class F, int N, typename...>
struct fn_typelist {};
template<typename...>
struct typelist {};
template<template<typename...> class F, int N, typename... Ts>
typelist<fn_typelist<F, N, Ts>...> layered(typelist<Ts...>);
template<template<typename...> class F, typename... Ts, typename... Us>
auto operator+(fn_typelist<F, sizeof...(Ts) + sizeof...(Us), Ts...>&&,
fn_typelist<F, sizeof...(Ts) + sizeof...(Us), Us...>&&)
-> F<Ts..., Us...>;
template<template<typename...> class F, int N, typename... Ts, typename... Us>
auto operator+(const fn_typelist<F, N, Ts...>&,
const fn_typelist<F, N, Us...>&)
-> fn_typelist<F, N, Ts..., Us...>;
template<typename... Ts, typename... Us>
auto operator+(typelist<Ts...>, typelist<Us...>)
-> typelist<Ts..., Us...>;
template<typename T, typename... Us>
auto operator*(typelist<T>, typelist<Us...>)
-> typelist<decltype(T{} + Us{})...>;
template<typename... Ts, typename TL>
auto operator^(typelist<Ts...>, TL tl)
-> decltype(((typelist<Ts>{} * tl) + ...));
template<template<typename...> class F, typename... TLs>
using product_apply_t = decltype((layered<F, sizeof...(TLs)>(TLs{}) ^ ...));
And you use as
struct A0;
struct A1;
struct B0;
struct B1;
struct C0;
struct C1;
struct C2;
using t1 = typelist<A0, A1>;
using t2 = typelist<B0, B1>;
using t3 = typelist<C0, C1, C2>;
template<typename...>
struct fn {};
using p1 = product_apply_t<fn, t1, t2>;
using p2 = product_apply_t<fn, t1, t2, t3>;
using expect1 = typelist<fn<A0, B0>,
fn<A0, B1>,
fn<A1, B0>,
fn<A1, B1>>;
using expect2 = typelist<fn<A0, B0, C0>,
fn<A0, B0, C1>,
fn<A0, B0, C2>,
fn<A0, B1, C0>,
fn<A0, B1, C1>,
fn<A0, B1, C2>,
fn<A1, B0, C0>,
fn<A1, B0, C1>,
fn<A1, B0, C2>,
fn<A1, B1, C0>,
fn<A1, B1, C1>,
fn<A1, B1, C2>>;
static_assert(std::is_same_v<p1, expect1>);
static_assert(std::is_same_v<p2, expect2>);
Where fn can be swapped with any class template or template alias with suitable parameters.
This instantiates the first (n-1)-ary cartesian product then applies the provided meta function at the n-ary cartesian product. Not being familiar with compilers, I have no idea whether this confers any speedup in compilation times.
The implementation is arcane, if you want to ask about it, it likely means you should just stick with producing the pack and iterating. Or Boost.
|
71,981,096 | 71,987,740 | Is there a way to start a new thread from dialog and use it in mainwindow in qt? | I have a function that downloads a torrent file. I need to download the torrent in a separate thread from the GUI thread, so I used QtConcurrent::run to start the download in another thread, but I started the download in a dialog and the dialog closes immediatly after the download has started, and (I'm new to qt, so I think) closing the dialog, the dialog object gets deleted and with the dialog QFuture and QFutureWatcher are also deleted and, since QFutureWatcher doesn't exists anymore, it doesn't emit the finished signal. Can someone tell me how to fix this and if what I wrote above is true?
Here is the code i use to start the download:
mainwindow.cpp
void MainWindow::on_downloadButton_clicked {
DownloadDialog ddl_dial;
ddl_dial.exec();
}
downloaddiaolg.cpp
on_finishButton_clicked() {
TorrentDDL tddl;
QFutureWatcher<void> *watcher = new QFutureWatcher<void>;
QFuture<void> tddl_thread = QtConcurrent::run(&TorrentDDL::download,
&tddl, magnet_str_url, file_path);
watcher->setFuture(tddl_thread);
close();
}
| Dialog gets deleted because it goes out of scope because it's instantiated on stack. Use heap.
DownloadDialog* ddl_dial = new DownloadDialog(this);
ddl_dial->exec();
Don't forget to delete it at some point to avoid memory leak.
|
71,981,297 | 71,981,551 | How to run method/function on a separate thread in c++ | I am a beginner to c++, so I don't know much
here is a function
void example(){
for(int i=0; i<5; i++){
// do stuff
}
}
if I call this function, it will wait for it to be finished before continuing
int main(){
example();
otherThingsGoHere();
otherThingsGoHere();
otherThingsGoHere();
return 0;
}
the otherThingsGoHere() doesn't get called until example() is done
my goal is to have that function be able to loop 60/70 fps in a loop forever
and I did get it working, except nothing below that will happen since it is in an infinite loop.
I've been a c# developer for some time and I know that in c#, you can use async functions to run on a seperate thread. How do I impliment something like this in c++?
Edit: I am not asking for you to put the otherThingsGoHere in front of the main because the other things is going to be another loop, so I need both of them to run at the same time
| You need to use a std::thread and run the example() function from that new thread.
A std::thread can be started when constructed with a function to run.
It will run potentially in parallel to the main thread running the otherThingsGoHere.
I wrote potentially because it depends on your system and number of cores. If you have a PC with multiple cores it can actually run like that.
Before main() exits it should wait for the other thread to end gracefully, by calling thread::join().
A minimal example for your case would be:
#include <thread>
#include <iostream>
void example() {
for (int i = 0; i<5; i++) {
std::cout << "thread...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void otherThingsGoHere() {
std::cout << "do other things ...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
int main() {
std::thread t{ example };
otherThingsGoHere();
otherThingsGoHere();
otherThingsGoHere();
t.join();
return 0;
}
Some more info here: Simple example of threading in C++
|
71,981,298 | 71,981,356 | Cmake include header only library with -I option | I have a header only library that is contained in a "headers/" directory in the main project. When compiling from terminal I include it with #include "symbolicc++.h", but I need to pass the option -I "headers/" when compiling with g++. How can I include this in a Cmake project? (And also, in general how can I pass other option such as -pthread to Cmake?
| Adding include directories in CMake is done by using the target_include_directories directive.
Use it this way (in your CMakeLists.txt):
target_include_directories(${TARGET_NAME} PUBLIC ${SOME_INCLUDE_DIR})
Some more info: target_include_directories
|
71,981,501 | 71,985,008 | Why #define variable in library is overridden from #define in calling application? | I am trying to a make plugin system which will have a header file for all plugins to include. In that header the version of the plugin system is defined in a #define like so:
PluginHeader.hpp:
#define PLUGIN_SYSTEM_VERSION "00.001"
class PluginSystem
{
public:
string GetSystemVersion(){return PLUGIN_SYSTEM_VERSION; }
void MyPluginDoStuff(){...}
}
I compile my plugin with this header in a dll and export it. Afterwards, i import it in the main application and i change the value of the #define in the calling application to be "00.002". If i call the method GetSystemVersion in the dll, then i am getting the new value "00.002".
Is this the expected behavior? How can i make the dll keep its defined value?
| It is neither expected nor unexpected behaviour. Your program has undefined behaviour, so any outcome (whether it seems "right" or not) is possible.
Your member function PluginSystem::GetSystemVersion() is defined (implemented) within its class definition, so is implicitly inline.
The problem is, by having different definitions of the macro PLUGIN_SYSTEM_VERSION in different compilation units (e.g. in your DLL and in a separate source file that includes your header), you cause your program to have multiple definitions of PluginSystem::GetSystemVersion() (and, in fact, the whole class PluginSystem) in your program. If those definitions aren't exactly the same, you're breaking the one-definition rule. Which for an inlined function (and for a class) means that all definitions seen by different source files must be identical.
Breaking the one-definition rule means your program has undefined behaviour. Seeing different versions of an inline function being called in different compilation units (e.g. the DLL version called in some situations but not others) is one possible symptom of that.
If you want to have the function in the DLL, then
Change the class definition so that the function is not inline within the class definition, and ensure that class definition is used consistently everywhere (both in all source files for your program, and in all source files for the DLL) - for example, by including the same header everywhere it is needed;
In exactly one source file, for the DLL, include exactly ONE definition of the function outside the class definition.
Although not technically necessary, I'd encourage you to avoid using macros (other than include guards) in the header (or, even, using a macro for it at all - there are alternatives). If you must have a macro PLUGIN_SYSTEM_VERSION, define it locally to the single source file that defines PluginSystem::GetSystemVersion(). That avoids the possibility of confusing yourself (and increasing chances of getting unexpected behaviours) by having different incantations of PLUGIN_SYSTEM_VERSION (and code affected by it) in different parts of your program.
|
71,981,976 | 71,982,014 | What are the differences between "T a", "T a()" and "T a=T()" where T is a class? | Let T a C++ class.
Is there any difference in behaviour between the following three instructions?
T a;
T a();
T a = T();
Does the fact that T provides an explicit definition for a constructor that takes no parameter change anything with respect to the question?
Follow-up question: what about if T provides a definition for a constructor that takes at least one parameter? Will there then be a difference in behaviour between the following two instructions (in this example I assume that the constructor takes exactly one parameter)?
T a(my_parameter);
T a = T(my_parameter);
| T a; performs default initialization.
T a = T(); performs value initialization.
T a(); does not declare a variable named a. It actually declares a function named a, which takes no arguments and whose return type is T.
The difference between default initialization and value initialization is discussed here.
|
71,982,220 | 71,990,718 | Boost.Log: register attributes manually | In my code using Boost.Log I register a formatter for my log output
register_simple_formatter_factory<LogLevel, char>("Severity");
This worked as expected for some time but now I tried to build on a different platform and are getting a linker error
undefined reference to `void boost::log::v2s_mt_posix::register_formatter_factory<char>(boost::log::v2s_mt_posix::attribute_name const&, boost::shared_ptr<boost::log::v2s_mt_posix::formatter_factory<char> > const&)'
My guess is that this is because the installed library from the package repository was build with BOOST_LOG_WITHOUT_DEFAULT_FACTORIES defined. According to the Boost.Log documentation this means that
the user will have to register all attributes in the library before
parsing any filters or formatters from strings.
But how do I do this? What specifically do I have to replace my call to register_simple_formatter_factory with to have the same effect.
|
My guess is that this is because the installed library from the package repository was build with BOOST_LOG_WITHOUT_DEFAULT_FACTORIES defined.
No, this is not the reason for the linking error. Disabling default factories does not remove factory registration APIs.
But how do I do this? What specifically do I have to replace my call to register_simple_formatter_factory with to have the same effect.
You don't need to replace register_simple_formatter_factory with anything. On the contrary, you must call register_simple_formatter_factory or register_formatter_factory for every attribute you use, even if you didn't have to before. Same for filters (register_filter_factory, register_simple_filter_factory). Where previously the default factories were used, you must now create and register ones manually.
Regarding linking errors, check this first. Make sure the namespace names in the library you link with match those in the linker error. If not, define configuration macros to rectify the mismatch.
Also, make sure you're linking with boost_log_setup, not just boost_log. boost_log_setup should go before boost_log in the linker command line.
|
71,982,437 | 71,982,547 | Why does this code give no output on online C++ compilers? | I was experimenting with a statement in C++ using online compilers. When I try to run this specific code
cout << num[i] + " " + num[i];
The online compilers give no output. I can change the + symbol to << but I want to know the reason that the code does not give any output on these online compilers.
Online compilers that I tried are onlinegdb, programiz, and jdoodle.
#include <iostream>
#include <string>
int main() {
std::string num = "123";
int i = 0;
std::cout << num[i] + " " + num[i];
return 0;
}
| C++ is not like JavaScript or many higher-level languages, as in you may not delimit you data with +'s or ,'s. As shown in Lewis' answer, each item you wish to have printed must be separated by an insertion delimiter (<<). As for extracting, you may use the extraction delimiter (>>).
In your case, you are doing mathematical operations on the the characters themselves (adding together their numerical ASCII representations together, which could print unprintable and invisible characters). The printable ASCII characters range from 32 (space character) to 127 (delete character) (base 10). When summing '1' + ' ' + '1' you are left with (49 + 32 + 49) or (130) which exceeds the printable character range. Or you may also be accessing garbage as @pm100 said in the comments due to pointer arithmetic.
Here is an example of using the insertion operator:
#include <iostream>
int main(void) {
int some_int = 1;
std::cout << "this is my " << some_int << "st answer on StackOverflow :)"
<< std::endl;
return 0;
}
And as for the extraction operator:
#include <iostream>
int main(void) {
int num;
std::cout << "Enter an integer: ";
std::cin >> num; // stores the input into the `num` variable
std::cout << "The number is: " << num << std::endl;
return 0;
}
Pointer arithmetic:
const char* get_filename(const char* _path, size_t _offset) {
return (_path + _offset);
}
// This is an example
//
// path = "path/to/my/file/file.txt";
// offset ^ ^
// 0 |
// + 16 ------------|
// path = "file.txt";
|
71,982,681 | 71,982,724 | How could I fix the undefined identifier error in the bool functions of my program? | I was doing an assignment for my class but I cannot see how to fix the undefined variable error for the N under grid[][N]. I was wondering if anyone here would mind showing me in the right direction? This program determines the locations of peaks in an elevation grid of data
#include <iostream> //Required for cin, cout
#include <fstream> //Required for ifstream
#include <string> //Required for string
#include <cmath> //Required for calculations
using namespace std;
//Function prototypes
bool isPeak(const double grid[][N], int i, int j);
int main()
{
//Object declaration
int const N{ 25 };
int nrows, ncols;
double elevation[N][N];
string filename;
ifstream file1;
//Prompt user for file name and open the named file
cout << "Enter the name of the input file: \n";
cin >> filename;
file1.open(filename);
if (file1.fail()) //Triggers if the file name is wrong or can't open the file
{
cerr << "Error opening input file \n";
exit(1);
}
file1 >> nrows >> ncols;
if (nrows > N || ncols >> N) //Triggers if the grid is too large
{
cerr << "Grid is too large, adjust the input.";
exit(1);
}
//Read the information from data file into array
for (int i = 0; i < nrows; ++i)
{
for (int j = 0; j < ncols; ++j)
{
file1 >> elevation[i][j];
}
}
//Determine and print peak locations
cout << "Top left point defined as row 0, column 0 \n";
for (int i = 1; i < nrows - 1; ++i)
{
for (int j = 1; j < ncols - 1; ++j)
{
if (isPeak(elevation, i, j))
{
cout << "Peak at row: " << i << " column: " << j << endl;
}
}
}
//Close file
file1.close();
//Exit program return 0;
}
bool isPeak(const double grid[][N], int i, int j)
{
if ((grid[i - 1][j] < grid[i][j]) &&
(grid[i + 1][j] < grid[i][j]) &&
(grid[i][j - 1] < grid[i][j]) &&
(grid[i][j + 1] < grid[i][j]))
return true;
else
return false;
}
The grid data is a text file with the following points:
5039 5127 5238 5259 5248 5310 5299
5150 5392 5410 5401 5320 5820 5321
5290 5560 5490 5421 5530 5831 5210
5110 5429 5430 5411 5459 5630 5319
4920 5129 4921 5821 4722 4921 5129
5023 5129 4822 4872 4794 4862 4245
| As other users pointed out, your N is defined in the main() scope, not in global. But the definition of a isPeak() function is in global scope. Thus the compiler can not see the N you are requiring him to see.
In order to solve the problem you can just define N in global scope (outside the main)
#include <iostream> //Required for cin, cout
#include <fstream> //Required for ifstream
#include <string> //Required for string
#include <cmath> //Required for calculations
using namespace std;
// here we define N
const int N = 25;
//Function prototypes
bool isPeak(const double grid[][N], int i, int j);
...
|
71,983,287 | 71,983,394 | Specialize template function to return vector | Let's say I have a reader class over a file:
class Reader {
public:
template <class T>
T Read();
};
Its only function is the Read function that reads any arithmetic type (static_assert(std::is_arithmetic_v<T>)) from a file. Now I want to create a specialization of that function, which reads a vector from the file. How would I go about doing that with templates? Something like the following doesn't work:
template <class T>
std::vector<T> Read<std::vector<T>>();
error: function template partial specialization is not allowed
std::vector<U> Read<std::vector<U>>();
^ ~~~~~~~~~~~~~~~~
| You can't partially specialize functions. You can overload them though, but the way of doing it is not obvious, since your function doesn't take any parameters.
First, you need a way to check if a type is a std::vector<??>:
template <typename T> struct IsVector : std::false_type {};
template <typename ...P> struct IsVector<std::vector<P...>> : std::true_type {};
Then you can plug it into requires:
template <typename T>
T Read()
{
// Generic overload
}
template <typename T> requires IsVector<T>::value
T Read()
{
// Vector overload
}
Alternatively, you could have a single function, with if constexpr (IsVector<T>::value) inside.
|
71,983,747 | 71,986,596 | Correct input of a phone number with an input mask | Asked the last question, regarding the mask and how to put the cursor at the end of the typed text, but did not receive an answer. Trying to figure it out on my own, I realized that the question was asked very superficially. So. I tried to delve into the logic, looked at examples on different sites.
ui->lineEdit_newClientPhone->setInputMask("+7\\(999\\)999\\-99\\-99;_");
What was my original idea - when you click the mouse, or when you get focus, check the line in a loop and put the cursor in the place of the first "__". The idea failed very quickly, as soon as I debugged the line ui->lineEdit->text() , and realized that the line consists only of the characters that are in the mask, without the "filler" (_). As a result, I had the line +7()--. The next idea was this, after much torment: I tried to come up with some complex mathematical calculations, like going through a cycle from the end of the string, as soon as part of the string becomes not equal to '(' or ')' or '-' - calculate the position cursor. (considering, again, the characters "( ) -") It seems that something even happened:
if(event->type() == QEvent::MouseButtonPress){
int a = ui->lineEdit_newClientPhone->text().length();
switch(a){
case 6: case 7: case 8:
ui->lineEdit_newClientPhone->setCursorPosition(a - 3);
break;
case 9: case 10:
ui->lineEdit_newClientPhone->setCursorPosition(a - 2);
break;
case 11: case 12:
ui->lineEdit_newClientPhone->setCursorPosition(a - 1);
break;
case 13: case 14:
ui->lineEdit_newClientPhone->setCursorPosition(a);
break;
}
}
But still hit some strange behavior, because when you click the mouse, the cursor is STILL put in the place where the mouse was poked. Despite the fact that putting the above switch into a button seems to work correctly.
I even tried to process elementary logic - when receiving focus, the cursor would receive index 4, that is, it would move to the first position necessary for introduction - but here the situation is the same as described above.
Maybe i need to use the validator directly with the line? Now there is a validator, here is its code:
QRegularExpression numberRegex ("^\\+\\d{1,1}\\(\\d{3,3}\\)\\d{3,3}\\-\\d{2,2}\\-\\d{2,2}$");
QRegularExpressionValidator *numberValidator = new QRegularExpressionValidator (numberRegex);
But it is used to check the correct spelling of a phone number. Further in the code, I check the validity of the entered string and then perform the necessary logic.
if(numberValidator->validate(a, b) == QValidator::Acceptable){
...
}
And what can I do? What is a more competent, and most importantly working, solution for creating the correct filling in of a phone number with a mask? In general, without all these "frills" - the mask performs its functions, but insofar as a large number of numbers will need to be entered in the program, managers will not be very happy with the need to aim the mouse at the required place for dialing.
| You are calling text() method, according to Qt doc:
When an input mask is set, the text() method returns a modified copy
of the line edit content where all the blank characters have been
removed. The unmodified content can be read using displayText().
So all you should do is finding symbol _ from template and setting cursor to it's position:
if(event->type() == QEvent::MouseButtonPress)
{
int pos = ui->lineEdit_newClientPhone->displayText()
.indexOf("_");
int last_pos = ui->lineEdit_newClientPhone->displayText().length();
ui->lineEdit_newClientPhone->setCursorPosition(
pos == -1 ? last_pos : pos
);
return true;
}
|
71,983,947 | 72,088,887 | Best HID device communication libary C++ | I want to send bytes to a HID device.
I've allready tried libhid but I can't get it to work.
Does anyone know a libary or a easy way to send bytes via. HID in C++.
Any help is appreciated.
| Check hidapi lib.
Also will be usefull for you same question on SO.
|
71,984,025 | 71,984,865 | Yet another C++ pointer to array question | I haven't written C++ for over 25 years and evidently I've forgotten a lot, and the compilers are now far more strict than they used to be. Consequently, I'm struggling and failing to create a dynamically allocated array of pointers to arrays of 8 unsigned char.
I believe I need a single variable that's a pointer.
I expect that variable to be assigned at runtime to point at a dynamically allocated array of pointers.
Each of the resulting pointers would then be assigned to point to an array of 8 unsigned char.
I think that the variable declaration for my array should be:
int (**arr)[8];
but I'm failing to work out how to allocate the storage.
For the first step I have tried a number of variations on this idea:
arr = new (int*[8])[4];
but all have been rejected as type incompatible, or flat out syntax errors. In desperation, I also tried:
arr = malloc(4 * sizeof(void *));
which was rejected with "cannot convert ‘void*’ to ‘int (**)[8]’" so I tried a cast:
arr = (int**[8])malloc(4 * sizeof(void *));
Which still failed.
EDIT:
In light of comments so far, first, I'm writing in C++, for an ESP32 device, and have now progressed to these efforts (still failing)
arr = new (int(*)[8])[4]; // array bound forbidden after parenthesized type
and
arr = new (int(*)[])[4]; // cannot convert ‘int (**)[]’ to ‘int (**)[8]’
It's clear from the comments that "I need to relearn a ton of stuff", and even "this isn't the best way of doing it", but for now I would like to just get the job done. Can anyone simply tell me a) if my variable declaration is sound, and b) how do I allocate the initial array of pointers?
| I believe you want to get to know ** double pointer and how to use them.
// explanation of what double pointer is.
int **arr1; //double pointer: is a pointer to point to pointer
// example
int* p = new int(1);
arr1 = &p; // points to pointer int*, note the "&" affront which returns the memory address of p.
arr1 = new int*[10]; // points to int*, "new" returns the memory address of newly allocated memory space.
// harder example, how to point to a double array [][]
int num_rows = 10;
arr1 = new int*[num_rows];
for (int i = 0; i < num_rows; ++i)
{
int num_cols = i + 1; // the column length can be different for each row
arr1[i] = new int[num_cols];
for (int j = 0; j < num_cols; ++j)
arr1[i][j] = i;
}
note that ** points not only those rows with fixed length, it can point to unequal length of data rows as shown in example. pay care to track the row lengths or just use double array.
|
71,984,101 | 71,984,165 | member function pointers to virtual functions | How is the information about ptr to a virtual member function vs. non virtual function encoded within a function pointer. Clearly this is compiler dependent, but I would like to understand techniques used to encode this information.
#include <cassert>
struct X {
virtual void f() {
}
void f1() {
}
};
struct Y : X {
void f() {
assert(0); // does trigger
}
};
int main() {
auto ptr = &X::f;
X *p = new Y();
(p->*ptr)();
}
| A non-virtual class method is, basically, an ordinary function, so a pointer to a non-virtual class method is functionally equivalent to an ordinary function pointer, the function's address.
Every non-static class method, whether virtual or not, receives an internal pointer. You know it as "this". This is, typically, an additional, hidden function parameter.
Every class with virtual inheritance has a hidden internal pointer as one of its class members. It's generated by the compiler and the compiler automatically generates the appropriate code to initialize it when an instance of the class gets created. This pointer points to compiler-generated metadata that, amongst other things, records the pointer to the metadata for the instantiated class and what all the real overridden virtual functions are, for that instance of the class.
A pointer to a virtual class method is an address of a function that digs into this, and uses the this's virtual function dispatch metadata to look up the actual, instantiated class and then use the hidden pointer to virtual class's metadata to look up the appropriate virtual function override, for this object, then (after a few more bookkeeping procedures) jumps to the appropriate, real, virtual function.
So the address of a virtual function is, typically, also an address of a function, except that it's not any specific virtual function, but rather a compiler-generated function that figures out what "real" object it's being invoked for and its appropriate overridden virtual function.
This is the capsule summary of a typical compiler implementation. Some details have been omitted. There are minor variations that differ from compiler to compiler.
|
71,984,127 | 71,984,331 | Is overloading on universal references now much safer with concepts in c++ 20 | In the book "Effective Modern C++" by Scott Meyers the advice is given (item 26/27) to "Avoid overloading on universal references". His rationale for this is that in almost all calls to an overloaded function that includes a universal reference, the compiler resolves to the universal reference even though that is often not the function you intend for it to resolve.
(so this code is bad I think?)
template <typename T>
void foo(T&& t) {
// some sort of perfect forwarding
}
void foo(string&& t) {
// some sort of move operation
}
The example above is highly contrived and could likely be replaced with 2 functions.
Another example that I think would be harder to resolve and is far less contrived is one he actually gives in Item 26.
class Foo {
// a decent amount of private data that would take a while to copy
public:
// perfect forwarding constructor, usually the compiler resolves to this...
template <typename T>
explicit Foo(T&& t) : /* forward the information for construction */ {}
// constructor with some sort of rValue
explicit Foo(int);
// both the below are created by the compiler he says
// move constructor
Foo(Foo&& foo);
// copy constructor (used whenever the value passed in is const)
Foo(const Foo& foo);
}
// somewhere else in the code
Foo f{5};
auto f_clone(f);
Scott explains that instead of calling a move constructor or copy constructor, the forwarding constructor gets called in auto f_clone(f) because the compiler rules are to resolve to the forward constructor first.
In the book, he explains alternatives to this and a few other examples of overloading on a universal reference. Most of them seem like good solutions for C++11/14/17 but I was thinking there were simpler ways to solve these problems with C++20 concepts. the code would be identical to the code above except for some sort of constraint on the forwarding constructor:
template <typename T>
requires = !(typename Foo) // not sure what would need to be put here, this is just a guess
explicit Foo(T&& t) : /* forward the information for construction */ {}
I don't know if that would be the correct syntax, I'm super new to C++ concepts
To me, C++ concepts applied to the forwarding function seem like a general solution that could be applied in every case but I'm not sure
there are multiple parts to my question:
is there even a way to disallow a specific type using C++ concepts? (perhaps similar to what I did)
is there a better way to tell the compiler not to use the forwarding constructor? (I don't want to have to make the variable I'm copying constant or explicitly define the copy/move constructors if I don't need to)
If there is a way to do what I'm suggesting, would this be a universally applicable solution to the problem Scott Meyers expresses?
Does applying a template constraint to a type automatically stop the type from being a universal reference?
| I would say no. I mean, concepts help, because the syntax is nicer than what we had before, but it's still the same problem.
Here's a real-life example: std::any is constructible from any type that is copy constructible. So there you might start with:
struct any {
template <class T>
requires std::copy_constructible<std::decay_t<T>>
any(T&&);
any(any const&);
};
The problem is, when you do something like this:
any a = 42; // calls any(T&&), with T=int
any b = a; // calls any(T&&), with T=any
Because any itself is, of course, copy constructible. This makes the constructor template viable, and a better match since it's a less-const-qualified reference.
So in order to avoid that (because we want b to hold an int, and not hold an any that holds an int) we have to remove ourselves from consideration:
struct any {
template <class T>
requires std::copy_constructible<std::decay_t<T>>
&& (!std::same_as<std::decay_t<T>, any>)
any(T&&);
any(any const&);
};
This is the same thing we had to do in C++17 and earlier when Scott Meyers wrote his book. At least, it's the same mechanism for resolving the problem - even if the syntax is better.
|
71,984,263 | 71,984,319 | 0 bytes in 1 blocks are definitely lost in loss record 1 of 1 | I'm learning C/C++ as a newcomer from java in school and since it is weekend, I can't get help from there. I got an error like this:
==18== 0 bytes in 1 blocks are definitely lost in loss record 1 of 1
==18== at 0x483C583: operator new[](unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==18== by 0x109536: Table::Table(unsigned long) (taul2.cpp:38)
==18== by 0x1093CF: main (taul2.cpp:108)
main:
Table nums(7);
nums.add(1); nums.add(2);
cout << nums<< endl;
Table nums2;
taul.place(nums);
cout << nums2<< endl;
Table nums3; // line 108
cout << nums3 << endl;
return 0;
Table:
class Table{
size_t max_size;
size_t amount;
int *numbers;
int fail;
public:
Table(size_t size=0)
{
fail= 0;
max_size = 0;
numbers = new int[size]; // line 38
if ( numbers ) max_size = size;
lkm = 0;
}
~Table() { if ( max_size != 0 ) delete [] numbers; max_size = 0; }
/* ... */
}
The error only occurs on nums3 which length is 0, debugger shows that it goes to the ~Table method, just like all the others, but it is the only 1 with errors.
| Even if you new 0 bytes, you still have to delete it. With every allocation, there's a bit of additional overhead beyond the number of bytes you asked for. (e.g. entry in the heap, the pointer itself, etc...).
Side note: new items[0] does not return nullptr. And even if it did, delete [] nullptr is perfectly OK and safe.
Change your destructor from
~Table() { if ( max_size != 0 ) delete [] numbers; max_size = 0; }
To this:
~Table() {
delete [] numbers;
}
|
71,984,693 | 71,984,700 | Intermittent issue getting input | Can someone explain to me what's wrong with this code? It works sometimes, i.e. if I input 5, 5, 5, -1 on the terminal, it'll return 15. But other times, it returns 0.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int input;
vector<int> input_vector;
cout << "Enter -1 when done" << endl;;
cout << "Your int: ";
cin >> input;
while (input != -1) {
input_vector.push_back(input);
cout << "Your int: ";
cin >> input;
}
int sum = 0;
for (auto i : input_vector) {
cout << "i: " << input_vector[i] << endl;
sum += input_vector[i];
}
cout << "Sum: " << sum << endl;
return 0;
}
| You use a range-based notation for (auto i : input_vector) which gives for i the actual values stored in the array. But then you use it as input_vector[i]. This is wrong: i is the value of the element, not the index. So replace input_vector[i] by i.
for (auto i : input_vector) {
cout << "i: " << i << endl;
sum += i;
}
Note that now you don't have the index any more, but for calculating a sum you don't need that.
|
71,985,273 | 71,986,567 | Template and anonymous namespace Issue | So I am updating some C++11 code to use gcc-11, and have run into a issue...
Namely, it appears that in gcc-11 the constructor symbol, for a class, which is explicitly instantiated, does not exist if the constructor uses a type from a template class, defined in an anonymous namespace.
A simplified example that produces the issue can be seen below.
Clang-12 and gcc-8 do not exhibit this behavior and export the symbols (as I would have expected).
template.h:
#pragma once
namespace {
template <typename T>
struct MyAnonTempStruct
{
typedef float BaseType;
};
}
template <typename T>
class MyTemplateClass
{
public:
typedef typename MyAnonTempStruct<T>::BaseType BaseType;
public:
MyTemplateClass(const BaseType* array);
};
template.cpp:
#include "template.h"
template <typename T>
MyTemplateClass<T>::MyTemplateClass(const BaseType* array)
{
}
template class MyTemplateClass<float>;
Using the compilation command
gcc -c -o template.o template.cpp
using nm I get the following symbol output for Clang-12 and gcc-8:
0000000000000000 W MyTemplateClass<float>::MyTemplateClass(float const*)
0000000000000000 W MyTemplateClass<float>::MyTemplateClass(float const*)
0000000000000000 n MyTemplateClass<float>::MyTemplateClass(float const*)
For gcc-11 I only get a text symbol:
0000000000000000 t MyTemplateClass<float>::MyTemplateClass(float const*)
If I mark the explicit specialization as extern in the header things work again in gcc-11.
ie, adding:
extern template class MyTemplateClass<float>;
So I guess my question is:
Is this expected behavior, and the fact that it previously worked was just because it was undefined, or is this some form of a miscompilation?
| Anonymous namespaces generally should not be used in header files. There are very few exceptions to this, and your use case is not one. You can use a namespace detail to suggest to people that the code inside is not meant for them to use.
GCC 11 is doing nothing wrong here, your code is simply not portable.
|
71,985,285 | 71,985,344 | Can static_cast be used in C source code compiled by C compiler? | I saw C-library with code that compiled by GCC 11 that do static_cast from C code and it perfectly fine for GCC.
But when I tried to compile this library in VisualStudio (MSVC) I got error: (this library can be compiled by older VS2019(pre-2021 update))
fatal error C1189: #error: STL1003: Unexpected compiler, expected C++ compiler.
And only comment about it I saw there https://github.com/ofiwg/libfabric/issues/7041#issuecomment-914839351
Hi! STL maintainer here. We made this change very recently in microsoft/STL#2148 which forbids including standard library headers from C programs.
Maybe im misunderstanding something, very confused.
| static_cast is part of the C++ language, and more importantly it is not part of the C language, so attempts to use static_cast<> should cause a C compiler to emit compile-time errors.
If you've seen it successfully used in "C source code" anyway... one likely explanation is that the "C source" code was being compiled as C++ source code by a C++ compiler. Since C++ is 99% backwards-compatible with C, most C source code can be compiled as C++ source code and will work, and in that scenario, static_cast could be part of the code and would compile.
Another possibility is that the compiler vendor got a bit sloppy and erroneously allowed a bit of their C++-specific functionality to execute even when compiling in the role of a C compiler, but hopefully that's not the case.
|
71,985,447 | 72,020,762 | C++ performance optimization for linear combination of large matrices? | I have a large tensor of floating point data with the dimensions 35k(rows) x 45(cols) x 150(slices) which I have stored in an armadillo cube container. I need to linearly combine all the 150 slices together in under 35 ms (a must for my application). The linear combination floating point weights are also stored in an armadillo container. My fastest implementation so far takes 70 ms, averaged over a window of 30 frames, and I don't seem to be able to beat that. Please note I'm allowed CPU parallel computations but not GPU.
I have tried multiple different ways of performing this linear combination but the following code seems to be the fastest I can get (70 ms) as I believe I'm maximizing the cache hit chances by fetching the largest possible contiguous memory chunk at each iteration.
Please note that Armadillo stores data in column major format. So in a tensor, it first stores the columns of the first channel, then the columns of the second channel, then third and so forth.
typedef std::chrono::system_clock Timer;
typedef std::chrono::duration<double> Duration;
int rows = 35000;
int cols = 45;
int slices = 150;
arma::fcube tensor(rows, cols, slices, arma::fill::randu);
arma::fvec w(slices, arma::fill::randu);
double overallTime = 0;
int window = 30;
for (int n = 0; n < window; n++) {
Timer::time_point start = Timer::now();
arma::fmat result(rows, cols, arma::fill::zeros);
for (int i = 0; i < slices; i++)
result += tensor.slice(i) * w(i);
Timer::time_point end = Timer::now();
Duration span = end - start;
double t = span.count();
overallTime += t;
cout << "n = " << n << " --> t = " << t * 1000.0 << " ms" << endl;
}
cout << endl << "average time = " << overallTime * 1000.0 / window << " ms" << endl;
I need to optimize this code by at least 2x and I would very much appreciate any suggestions.
| As @hbrerkere suggested in the comment section, by using the -O3 flag and making the following changes, the performance improved by almost 65%. The code now runs at 45 ms as opposed to the initial 70 ms.
int lastStep = (slices / 4 - 1) * 4;
int i = 0;
while (i <= lastStep) {
result += tensor.slice(i) * w_id(i) + tensor.slice(i + 1) * w_id(i + 1) + tensor.slice(i + 2) * w_id(i + 2) + tensor.slice(i + 3) * w_id(i + 3);
i += 4;
}
while (i < slices) {
result += tensor.slice(i) * w_id(i);
i++;
}
|
71,985,523 | 71,985,536 | Why is std::string not trivially destructible? | I'm a c++ noob and I've been reading about trivial destructibility.
From this article on trivial destructibility,
Trivially destructible types include scalar types, trivially copy
constructible classes and arrays of such types.
A trivially destructible class is a class (defined with class, struct
or union) that:
uses the implicitly defined destructor.
the destructor is not virtual.
its base class and non-static data members (if any) are themselves also trivially destructible types.
But apparently std::string is not trivially destructible. Why? Which of the above rules does std::string not satisfy?
std::cout << std::boolalpha
<< "std::string is trivially destructible? "
<< std::is_trivially_destructible<std::string>::value << '\n'
The above snippet returns the following output:
std::string is trivially destructible? false
| A std::string typically contains a pointer to dynamically allocated character data, so it needs an explicit destructor to deallocate that memory. So, if nothing else, it must either fail this criterion:
uses the implicitly defined destructor
or have a base class that fails it, in which case it fails this criterion:
its base class and non-static data members (if any) are themselves also trivially destructible types.
|
71,985,595 | 71,985,649 | How to set executable to Win32 in release mode | I've read on CMake's documentation that when calling add_executable, you can set the executable type to be Win32 by doing add_executable(target WIN32 source.cpp). I also know that you should use CMake generator expressions to check for build configurations like so:
target_compile_definitions(target PUBLIC
$<$<CONFIG:Debug>:DEBUG>
$<$<CONFIG:Release>:RELEASE>
)
However this won't work with add_executable. It treats it as a source file when I do add_executable(target $<$<CONFIG:Release>:WIN32> source.cpp) and so it fails. What is the correct way of doing setting the executable type to WIN32 only in release mode?
| I am not really sure it makes sense given a WIN32 executable and a non-WIN32 executable do not have the same entry point, so the code would need to change as well.
Still, here is how you would do it on CMake side:
add_executable(target source.cpp)
set_target_properties(target PROPERTIES WIN32_EXECUTABLE $<CONFIG:Release>)
Key point is the WIN32 flag in add_executable is just a shortcut to set the WIN32_EXECUTABLE property.
Note: I cannot test this sample atm so it depends on me having read those links properly ;)
|
71,985,957 | 71,986,021 | Can we declare constructor before member variables? | Can the constructer declared before the member variable alter its value?
I thought only the code below works,
struct test {
int a;
test(int t): a(t) {}
};
but I found the code below also works.
struct test {
test(int t): a(t) {}
int a;
};
Usually, in function, we cannot use the variable that is not declared. Why the code above is OK?
| Actually in C++ there's an exception that there's no need for forward declaration of functions and variable of a class/struct.
You can see my such examples on the internet like this:
class foo
{
public:
foo(int x) : my_var(x) {}
private:
int my_var;
};
The above is 100% valid.
You can also call a function of a class before it is defined like:
class bar
{
public:
bar()
{
this->my_below_func();
}
int my_below_func()
{
return 1;
}
};
Always remember that these tricks aren't going to work outside C++ classes/structs, you will need forward declaration of your functions and variables.
|
71,986,185 | 71,986,217 | How to use an object created inside a try block, outside of it? | Say I created an object inside a try block because I wanted to catch the exceptions thrown from it's constructor, how will I be able to use the object outside of that block?
//Inputs given to t5 can throw an exception from the constructor.
try {
Time t5(23, 59, 59);
}
catch (invalid_argument& e) {
cerr << "\n\nException while initializing t5: " << e.what() << endl;
}
In the case where an exception is thrown, I probably won't need to use it but in a case where it isn't thrown, I'll surely need it afterwards but an object created inside a block isn't accessible outside.
One solution I could think of was creating the object outside of block and then assigning an R-value object to it I create by explicitly calling the constructor like this:
Time t5;
try {
t5 = Time(23, 59, 59);
}
catch (invalid_argument& e) {
cerr << "\n\nException while initializing t5: " << e.what() << endl;
}
But this is doing unnecessary stuff like creating another object just for trying to catch an exception.
Are there any better ways to do it? Also, is throwing exceptions from a constructor a bad programming practice?
PS: I saw a similar question being asked but for C# and also, the solution given there is the same that I came up with but I believe that there should be a better way as I explained above.
Thank you.
| Depends on what kind of a default constructor Time has. If its constructor just zeroes three numbers, then your solution is ok.
If its default constructor is expensive (or doesn't exist at all), you can put it into std::optional:
std::optional<Time> t5;
try
{
t5.emplace(23, 59, 59);
}
// ...
|
71,986,332 | 71,986,349 | Why do we use dynamic allocation in a linked list? | In a linked list class, the code below is declaring Node<T> *newNode:
void LinkedList<T>::push_front(const T& val) {
Node<T> *newNode = new Node<T>(val);
newNode->next = head;
head = newNode;
if(newNode->next == NULL) tail = newNode;
}
Why do we use dynamic allocation? Can't we just write Node<T> newNode(val);?
I think since we are not making arrays of newNode, it is valid.
| A local variables such as Node<T> newNode(val); would be destroyed when exiting the function (or rather, when exiting the scope (aka braces, more or less)) that it was created in.
But for a linked list, you want the nodes to live longer; as long as you want them to.
|
71,986,415 | 71,989,304 | Does C++20 require of the implementations the use of IANA Time Zone Database? | C++20 <chrono> library comes with local time and time zone support. The interface of this library is compatible with that of IANA Time Zone Database, but the question is, does C++ Standard require that the implementation actually uses IANA Time Zone Database with all its historical data?
The online C++ reference claims that it does: see here. The C++ Standard itself contains a weaker statement:
[time.zone] describes an interface for accessing the IANA Time Zone Database that interoperates with sys_time and local_time.
This interface provides time zone support to both the civil calendar types ([time.cal]) and to user-defined calendars.
It only mentions the interface, but not the data. The subsequent description of the timezone library in the Standard makes no further reference to IANA Time Zone Database.
My conclusion is that C++ Reference is wrong, and the implementation is not required to use the IANA Time Zone Database. Can someone confirm if this conclusion is correct?
| The Library Working Group of the C++ Standards Committee wrestled with those words for quite a bit, trying to get them right. The intent is that the std::lib supplies the IANA Time Zone Database. And perhaps even more importantly, all three major std::lib vendors are on-board with that intent.
Not shown in the online standard is a bibliography section of the standard which contains:
IANA Time Zone Database. Available from: https://www.iana.org/time-zones
Note that std::chrono also supports user-written timezones as well. Here is an example of one1, and here is an example of its use:
#include "date/ptz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
auto now = system_clock::now();
auto tzp = Posix::time_zone{"EST5EDT,M3.2.0,M11.1.0"};
cout << zoned_time{tzp, now} << '\n';
}
This example models POSIX timezones and this example shows the current definition of "America/New_York" (without historical data preceding 2007).
1This example is coupled to the pre-C++20 chrono preview as opposed to std::chrono. To change it would only require references to namespace date be changed to namespace std::chrono.
|
71,986,909 | 71,988,721 | Load ECDSA private key with Crypto++ | I'm trying to load an EC key given as a byte array using Crypto++. Here is the key:
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIPQLO9zyl40X3lh1wbSR6S88aCsUvJr9R5n2pA3DbD9+oAoGCCqGSM49
AwEHoUQDQgAEs+nDydkW5F07yZPb/c05TSjzRJXCvD8Ni76ppfWJFOEOdM/WuHU6
zBMcdIzoY+LuqdZ8LgVlMBsnx8NwNvvFAA==
-----END EC PRIVATE KEY-----
And here is the same key as a byte array (assuming I didn't mess up the conversion):
uint8_t server_priv_key_[] = {
0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0xf4, 0x0b, 0x3b, 0xdc, 0xf2,
0x97, 0x8d, 0x17, 0xde, 0x58, 0x75, 0xc1, 0xb4, 0x91, 0xe9, 0x2f, 0x3c,
0x68, 0x2b, 0x14, 0xbc, 0x9a, 0xfd, 0x47, 0x99, 0xf6, 0xa4, 0x0d, 0xc3,
0x6c, 0x3f, 0x7e, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xb3, 0xe9, 0xc3,
0xc9, 0xd9, 0x16, 0xe4, 0x5d, 0x3b, 0xc9, 0x93, 0xdb, 0xfd, 0xcd, 0x39,
0x4d, 0x28, 0xf3, 0x44, 0x95, 0xc2, 0xbc, 0x3f, 0x0d, 0x8b, 0xbe, 0xa9,
0xa5, 0xf5, 0x89, 0x14, 0xe1, 0x0e, 0x74, 0xcf, 0xd6, 0xb8, 0x75, 0x3a,
0xcc, 0x13, 0x1c, 0x74, 0x8c, 0xe8, 0x63, 0xe2, 0xee, 0xa9, 0xd6, 0x7c,
0x2e, 0x05, 0x65, 0x30, 0x1b, 0x27, 0xc7, 0xc3, 0x70, 0x36, 0xfb, 0xc5,
0x00,
};
Finally, I'm loading the key like this:
ArraySource server_priv_key_source { server_priv_key_, sizeof(server_priv_key_), true };
ECDSA<ECP, SHA256>::PrivateKey server_priv_key;
server_priv_key.Load(server_priv_key_source);
However, the call to Load causes a "BER decode error" exception. What am I doing wrong?
| Your private key has the SEC1 format, but only the PKCS#8 format is supported (see here and here), so the key has to be converted, e.g. with OpenSSL:
openssl pkcs8 -topk8 -nocrypt -in <path to input-sec1-pem> -out <path to output-pkcs8-pem>
This results in (PEM encoded):
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg9As73PKXjRfeWHXB
tJHpLzxoKxS8mv1HmfakDcNsP36hRANCAASz6cPJ2RbkXTvJk9v9zTlNKPNElcK8
Pw2Lvqml9YkU4Q50z9a4dTrMExx0jOhj4u6p1nwuBWUwGyfHw3A2+8UA
-----END PRIVATE KEY-----
or as byte array (DER encoded):
uint8_t server_priv_key_[] = {
0x30, 0x81, 0x87, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d,
0x03, 0x01, 0x07, 0x04, 0x6d, 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20,
0xf4, 0x0b, 0x3b, 0xdc, 0xf2, 0x97, 0x8d, 0x17, 0xde, 0x58, 0x75, 0xc1,
0xb4, 0x91, 0xe9, 0x2f, 0x3c, 0x68, 0x2b, 0x14, 0xbc, 0x9a, 0xfd, 0x47,
0x99, 0xf6, 0xa4, 0x0d, 0xc3, 0x6c, 0x3f, 0x7e, 0xa1, 0x44, 0x03, 0x42,
0x00, 0x04, 0xb3, 0xe9, 0xc3, 0xc9, 0xd9, 0x16, 0xe4, 0x5d, 0x3b, 0xc9,
0x93, 0xdb, 0xfd, 0xcd, 0x39, 0x4d, 0x28, 0xf3, 0x44, 0x95, 0xc2, 0xbc,
0x3f, 0x0d, 0x8b, 0xbe, 0xa9, 0xa5, 0xf5, 0x89, 0x14, 0xe1, 0x0e, 0x74,
0xcf, 0xd6, 0xb8, 0x75, 0x3a, 0xcc, 0x13, 0x1c, 0x74, 0x8c, 0xe8, 0x63,
0xe2, 0xee, 0xa9, 0xd6, 0x7c, 0x2e, 0x05, 0x65, 0x30, 0x1b, 0x27, 0xc7,
0xc3, 0x70, 0x36, 0xfb, 0xc5, 0x00
};
In this format the key can be imported with the posted code.
Test:
In the following code, the private key is imported, a message is signed, the public key is derived from the imported private key, and the message is then successfully verified:
#include <osrng.h>
#include <eccrypto.h>
using namespace CryptoPP;
using namespace std;
...
uint8_t server_priv_key_[] = ... // the DER encoded PKCS#8 key above
// Import private key
ArraySource server_priv_key_source{ server_priv_key_, sizeof(server_priv_key_), true };
ECDSA<ECP, SHA256>::PrivateKey server_priv_key;
server_priv_key.Load(server_priv_key_source);
// Derive public key
ECDSA<ECP, SHA256>::PublicKey publicKey;
server_priv_key.MakePublicKey(publicKey);
// Sign
AutoSeededRandomPool prng;
ECDSA<ECP, SHA256>::Signer signer(server_priv_key);
size_t signatureLen = signer.MaxSignatureLength();
string signature(signatureLen, 0x00);
string msg = "The quick brown fox jumps over the lazy dog";
signatureLen = signer.SignMessage(prng, (const byte*)&msg[0], msg.size(), (byte*)&signature[0]);
signature.resize(signatureLen);
// Verify
ECDSA<ECP, SHA256>::Verifier verifier(publicKey);
bool result = verifier.VerifyMessage((const byte*)&msg[0], msg.size(), (const byte*)&signature[0], signature.size());
printf("%s", result ? "verified" : "failed"); // verified
|
71,986,924 | 71,987,054 | Calling child's overridden method from parent class | I want to practice C++ by coding a simple mobile phone application with an interchangeable system. I created a System base class and also created MyOS class which extends the System class. In the Phone class, I have a variable of System class because I think like in Java, you can assign it with child class. (eg. System sys = new MyOS();). But in C++ it calls the function in the base class.
What I want to work in C++ but it's in Java.
public class MyParent {
public void start() {
System.out.println("start() executed in MyParent");
}
}
public class MyChild extends MyParent {
@Override
public void start() {
System.out.println("start() excecuted in MyChild");
}
}
public class Inherit {
MyParent parent;
public Inherit(MyParent parent) {
this.parent = parent;
}
public void start() {
parent.start();
}
}
public class TestInherit {
public static void main(String[] args) {
Inherit i = new Inherit(new MyChild());
i.start();
}
}
Output: start() excecuted in MyChild
My current c++ code:
System.h
#pragma once
#include <iostream>
class System {
public:
void start() {
std::cout << "Booting System..." << std::endl;
}
};
MyOS.h
#pragma once
#include <iostream>
#include "System.h"
class MyOS: public System {
public:
// Override
void start() {
std::cout << "Booting MyOS..." << std::endl;
}
};
Phone.h
#pragma once
#include "System.h"
class Phone {
public:
Phone(System system) {
Phone::system = system;
}
void start() {
system.start();
}
private:
System system;
};
MyPhone.cpp
#include "MyOS.h"
#include "Phone.h"
#include "System.h"
int main() {
MyOS os;
Phone myPhone(os);
myPhone.start();
return 0;
}
Output: Booting System...
| If you're coming from java, you need to remember that every non-primitive variable or field in java is implicitly a pointer, so to make equivalent C++ code, you need to make all interclass references into pointers.
In addition, every method in java is implicitly virtual, so if you want to override them, you need an explicit virtual in C++.
So you end up with something like:
#include <iostream>
class System {
public:
virtual void start() {
std::cout << "Booting System..." << std::endl;
}
};
class MyOS: public System {
public:
// Override
void start() override {
std::cout << "Booting MyOS..." << std::endl;
}
};
class Phone {
public:
Phone(System *system) {
this->system = system;
}
void start() {
system->start();
}
private:
System *system;
};
int main() {
MyOS os;
Phone myPhone(&os);
myPhone.start();
return 0;
}
Of course, using raw pointers is a recipe for memory leaks and corruption, as C++ does not have built in garbage collection. So you generally want to use "smart" pointers instead -- either std::unique_ptr or std::shared_ptr
|
71,987,426 | 71,999,440 | Is member initializer list considered part of the body of a constructor or it it considered part of the declarator | I am learning about member initializer lists in C++. So consider the following example:
struct Person
{
public:
Person(int pAge): age(pAge)
// ^^^^^^^^^ is this member initializer formally part of the constructor body?
{
}
private:
int age = 0;
};
My first question is that is the member initializer age(pAge) formally part of the constructor's body. I mean i've read that a function's body starts from the opening { and end at the closing }. To my current understanding, there are four things involved here:
Ctor definition: This includes the whole
//this whole thing is ctor definition
Person(int pAge): age(pAge)
{
}
Member initializer: This is the age(pAge) part.
Ctor declaration: This is the Person(int pAge) part.
Ctor's body: This is the region between the opening { and the closing }.
My second question is that is the above given description correct? If not then what should be the correct meaning of those four terms according to the C++ standard: Ctor definition, Member initializer, Ctor declaration and Ctor's body.
PS: I've read this post which doesn't answer my question.
| As per [dcl.fct.def.general], which tells us the grammar of a function definition, a ctor-initializer is part of the function-body:
function-definition:
[...] function-body
function-body:
ctor-initializer_opt compound-statement
The compound-statement, as per [stmt.block], is, in this context, what OP refers to as "within braces" (block):
A compound statement (also known as a block) groups a sequence of
statements into a single statement.
compound-statement:
{ statement-seq_opt }
Whereas ctor-initializer, as per [class.base.init], is particularly allowed only for the special kind of functions that are constructors [emphasis mine]:
In the definition of a constructor for a class, initializers for
direct and virtual base class subobjects and non-static data members
can be specified by a ctor-initializer, which has the form
ctor-initializer:
: mem-initializer-list
With this, we can answer the OP's questions.
Is member initializer list considered part of the body of a constructor or it it considered part of the declarator
Yes, as per the above the member initializer, formally mem-initializer-list, is part of the function-body of the constructor.
My second question is that is the above given description correct?
1. Ctor definition: This includes the whole
//this whole thing is ctor definition
Person(int pAge): age(pAge)
{
}
Correct.
2. Member initializer: This is the age(pAge) part.
Correct, formally the mem-initializer-list (whereas : age(pAge) is the ctor-initializer
3. Ctor declaration: This is the Person(int pAge) part.
Not entirely correct: a definition is also a declaration. [dcl.fct] describe the rules of function declarations, and in simple terms, Person(int pAge); is a declaration that is not a definition, particularly here by omission of a function-body.
4. Ctor's body: This is the region between the opening { and the closing }.
Incorrect. The body of a function, as covered above, container also, optionally, a ctor-initializer. In OP's example, : age(pAge) {} is the function-body of the constructor.
|
71,987,443 | 71,987,603 | c++ : How does std::sort a vector of equal elements based on weak ordering principle | I am trying to understand how weak ordering works by reading this article : https://medium.com/@shiansu/strict-weak-ordering-and-the-c-stl-f7dcfa4d4e07
The main take away from it is :
Then for strict weak ordering we must have
For all x:
x < x is never true, everything should be equal to itself
If x < y then y < x cannot be true
If x < y and y < z then x < z, the ordering should be transitive
If x == y and y == z then x == z, equality should be transitive
How would the below code work ?
For example , if someone compares x1 and x2 my compare function will return false for both func(x1,x2) and func(x2,x1). Then weak ordering is broken because rule number 2 is broken I think . Is my understanding incorrect ?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct x
{
int a ;
x()
{
a = 3;
}
};
bool func(const x& x1,const x& x2)
{
if (x1.a < x2.a )
return true;
return false;
}
int main()
{
cout << "Hello World" << endl;
std::vector<x> vec;
x x1 , x2, x3 , x4 , x5, x6, x7;
x1.a = 5;
x2.a = 5;
x3.a = 5;
x7.a = 5;
vec.push_back(x1);
vec.push_back(x2);
vec.push_back(x3);
vec.push_back(x4);
vec.push_back(x5);
vec.push_back(x6);
vec.push_back(x7);
std::sort (vec.begin(), vec.end(), func);
return 0;
}
| The code is good.
When the values x1 and x2 are compared, rule 2 is satisfied: The rule says "IF x < y, THEN something else". Since the IF part is false (x1 is not less than x2), the entire statement is true.
That is how implications ("IF ... THEN ...") work. It is a basic rule of mathematical logic: when the precondition is not satisfied, the entire statement is true.
|
71,987,638 | 74,103,854 | With clang and libstdc++ on Linux, is it currently feasible to use any standard library types in a module interface? | So far it seems to me that including almost any libstdc++ header in a C++ module interface causes compile errors on clang 14.0.0 and the libstdc++ that comes bundled with GCC 11.2.0. I wonder if I am doing something wrong or if this is just not something that is supported yet. (I see that the Clang modules support is "partial", but haven't been able to find what is implemented and what is not.)
Here's a trivial module example that I got to work with clang-14 in Linux, linked with libstdc++. It demonstrates that libstdc++ headers can be used in a module implementation, but this example does not #include anything in the module interface:
// mod_if.cc
export module mod;
export int foo();
// mod.cc
module;
#include <iostream>
module mod;
int foo() {
std::cout << "Hello world from foo()" << std::endl;
return 42;
}
// use.cc
import mod;
#include <iostream>
int main() {
std::cout << foo() << std::endl;
}
This works:
$ CXXFLAGS="-std=c++20 -fmodules -fprebuilt-module-path=prebuilt"
$ clang++ -c $CXXFLAGS -Xclang -emit-module-interface -o prebuilt/mod.pcm mod_if.cc
$ clang++ -c $CXXFLAGS -fmodule-file=prebuilt/mod.pcm mod.cc -o mod.o
$ clang++ $CXXFLAGS use.cc mod.o prebuilt/mod.pcm -o use
$ ./use
Hello world from foo()
42
However, suppose I wanted foo to return a std::string:
// mod_if.cc
module;
#include <string>
export module mod;
export std::string foo();
// mod.cc
module;
#include <string>
module mod;
std::string foo() {
return "42";
}
// no use.cc needed since the error happens when building mod.cc
This does not compile (first of many similar errors shown):
$ clang++ -c $CXXFLAGS -Xclang -emit-module-interface -o prebuilt/mod.pcm mod_if.cc
$ clang++ -c $CXXFLAGS -fmodule-file=prebuilt/mod.pcm mod.cc -o mod.o
In file included from mod.cc:2:
In file included from /usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/string:40:
In file included from /usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/char_traits.h:39:
In file included from /usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/stl_algobase.h:64:
In file included from /usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/stl_pair.h:65:
/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/compare:348:33: error: redefinition of '__cmp_cat_id<std::partial_ordering>'
inline constexpr unsigned __cmp_cat_id<partial_ordering> = 2;
^
/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/stl_pair.h:65:11: note: '/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/compare' included multiple times, additional include site in header from module 'mod.<global>'
# include <compare>
^
/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/stl_pair.h:65:11: note: '/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/compare' included multiple times, additional include site in header from module '<global>'
# include <compare>
^
mod.cc:1:1: note: <global> defined here
module;
^
Is there currently a way to make this code work (without resorting to writing module maps for the libstdc++ headers)? Why does this error happen? It sounds strange that the inline constexpr declaration included in the global module fragment gets exported, but then I don't claim to understand modules well.
| Ok, this is something that sort of worked for a large project. Note that this was half a year ago, so the world may have moved on.
I ended up creating a single header, "sys.hh", that #includes pretty much all the system headers used in the project. What seems to be important is that nothing directly or indirectly #included by this file gets #included directly or indirectly (outside the module system) in anything that gets linked into the final binary.
My "sys.hh" looks something like this:
#include <algorithm>
#include <array>
#include <assert.h>
#include <atomic>
#include <bits/std_abs.h>
// 100+ lines omitted, including things like glib, gtk, libjpeg
#include <vector>
#include <x86intrin.h>
#include <zlib.h>
// Macros won't get exported, so whatever the code needs, redefine as
// constexpr (or consteval functions) here. Unfortunately, I don't think
// there's a way to retain the name of the macro; so add an underscore.
// Also put them in a namespace.
#define MEXP(X) constexpr auto X ## _ = X;
namespace sys {
MEXP(INTENT_PERCEPTUAL);
MEXP(INTENT_RELATIVE_COLORIMETRIC);
MEXP(INTENT_SATURATION);
MEXP(INTENT_ABSOLUTE_COLORIMETRIC);
MEXP(G_PRIORITY_DEFAULT_IDLE);
}
And my my modulemap file contains an entry like this:
module sys {
header "prebuilt/sys.hh"
use _Builtin_intrinsics
export *
}
Compiling this header/module is a bit of an incremental process; you will run into modules that fail to compile because they indirectly include the same headers, so you add them into this file and rebuild until it works.
Note that managing build dependencies becomes much more of a thing with modules. At least half a year ago no good (automatic) ways seemed to exist to discover what needs to be rebuilt. This is made trickier by the fact that the name of the module does not tell where it lives in the source code.
|
71,987,840 | 71,994,381 | Smart pointers cast c++17 apple clang | I'm trying to use arrays in smart pointers, but when I cast smart_ptr to weak_ptr using Apple clang I get an error (I use -std=c++17).
error: cannot initialize a member subobject of type 'std::weak_ptr<int []>::element_type *' (aka 'int (*)[]') with an lvalue of type 'std::shared_ptr<int []>::element_type *const' (aka 'int *const')
: __ptr_(__r.__ptr_),
Here is an example of code I'm trying to compile.
std::shared_ptr<int[]> ptr(new int[5]);
ptr[0] = 1;
ptr[1] = 2;
ptr[2] = 3;
std::weak_ptr<int[]> weakPtr(ptr);
std::cout << ptr[0] << std::endl;
P.S. I can't use std::array as I'm implementing my own container class.
| This seems to be a bug, where weak_ptr<T>::element_type should be defined as remove_extend_t<T>, but it is currently defined as T. On the other side, share_ptr<T>::element_type is correctly defined as remove_extend_t<T>.
This inconsistent caused the underlying type of shared_ptr<T[]> is T*, where the underlying type of weak_ptr<T[]> is T(*)[], thus you cannot assign the shared_ptr<T[]> to weak_ptr<T[]> as expected.
The bug was fixed in this commit: LWG3001 and should be included in a future release.
A work around is to probably use shared_ptr<std::array<int, 5>> and deduce the type for std::weak_ptr with weak_ptr weakPtr(ptr).
Note you will not be able to use shared_ptr::operator [] directly anymore. Instead, you would need to do get the element with (*ptr)[N].
|
71,988,033 | 71,988,083 | Sorting vector of objects by object's variable | I have a vector of objects. Each of these objects has 2 fields (the values of which can be repeated), e.g:
//myClass name = myClass(x,y)
myClass obj1 = myClass(2,5);
myClass obj2 = myClass(2,4);
myClass obj3 = myClass(1,5);
myClass obj4 = myClass(3,2);
std::vector<myClass> myVector;
myVector.push_back(obj1);
myVector.push_back(obj2);
myVector.push_back(obj3);
myVector.push_back(obj4);
I want to sort the vector. First it should be sorted by 1st values. If the values of the 1st variable is the same, then should be sorted by second variable. Vector after sorting should be like that:
obj3 //(1,5)
obj2 //(2,4)
obj1 //(2,5)
obj4 //(3,2)
I have wrote this simple code with bubble sort:
for (int i = 0; i < myVector.size(); i++)
{
for (int j = 0; j < myVector.size() - 1; j++)
{
if (myVector[j].x < myVector[j + 1].x)
std::swap(myVector[j], myVector[j + 1]);
}
}
Now myVector is sorted by first value, but how to sort elements, which first value it the same, by second value? Like in example?
| You can try something like that:
for (int i = 0; i < myVector.size(); i++)
{
for (int j = 0; j < myVector.size() - 1; j++)
{
if (myVector[j].x < myVector[j + 1].x)
{
std::swap(myVector[j], myVector[j + 1]);
}
else if (myVector[j].x == myVector[j + 1].x)
{
if (myVector[j].y < myVector[j + 1].y)
std::swap(myVector[j], myVector[j + 1]);
}
}
}
|
71,988,147 | 71,988,251 | How to loop this program if the user input 2 or more character? | #include<iostream>
#include<string>
int main(){
char find;
char find;
int times = 0;
string message;
cout <<"Enter a message a message: ";
getline(cin, message);
cout <<"Enter a character to be found: ";
cin >> find;
for(int i = 0; i<message.length(); i++){
if(message[i]== find){
times++;
}
}
cout <<"The character " << find <<" appeared " << times <<" times(s) in the message ";
}
output
Enter a message: hello
Enter a character to be found: ll
The character l appeared 2 times(s) in the message
| Try below code :
#include<iostream>
#include<string>
using namespace std;
int main() {
string find;
int times = 0;
string message;
cout << "Enter a message a message: ";
getline(cin, message);
cout << "Enter the character to be found: ";
cin >> find;
while (find.length() > 1) {
cout << "Enter only 1 character to be found: ";
cin >> find;
}
for (int j = 0; j < find.length(); j++)
{
times = 0;
for (int i = 0; i < message.length(); i++) {
if (message[i] == find[j]) {
times++;
}
}
cout << "The character " << find[j] << " appeared " << times << " times(s) in the message \n";
}
return 0;
}
Output:
Enter a message a message: aa bb ccc ddd
Enter the characters to be found: ab
Enter only 1 character to be found: ac
Enter only 1 character to be found: a
The character a appeared 2 times(s) in the message
|
71,988,229 | 71,988,900 | in Android Ndk 'malloc.h' file not found | i want use malloc lib when i create a new .c file and .h file .android studio tell me 'malloc.h' file not found.
I use CMake to compile.
is my CMakeLists.txt.
I am a ndk rookie.
cmake_minimum_required(VERSION 3.4.1)
add_library(
native-lib
SHARED
native-lib.cpp)
find_library(
log-lib
log)
target_link_libraries(
native-lib
jnigraphics
${log-lib})
This is the cpp folder structure
What modification should I make?
| I know. I need to add a .c file to add_library .
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
native-lib.cpp
stackblur.c)
|
71,989,024 | 71,989,126 | Can't compile a Crow sample - boost/optional.hpp: No such file or directory | I'd like to compile and test Crow C++ microframework in Debian Linux 11:
Download the latest crow.deb, currently crow-v1.0+1.deb.
Install it:
$ sudo dpkg -i crow-v1.0+1.deb
Selecting previously unselected package crow.
(Reading database ... 587955 files and directories currently installed.)
Preparing to unpack crow-v1.0+1.deb ...
Unpacking crow (1.0+1) ...
Setting up crow (1.0+1) ...
Create a .cpp file with a sample code from crowcpp.org:
$ echo '#include "crow.h"
int main()
{
crow::SimpleApp app;
CROW_ROUTE(app, "/")([](){
return "Hello world";
});
app.port(18080).run();
}' > crowtest.cpp
Try to compile it:
$ g++ crowtest.cpp -lpthread
In file included from /usr/include/crow.h:2,
from crowtest.cpp:1:
/usr/include/crow/query_string.h:9:10: fatal error: boost/optional.hpp: No such file or directory
9 | #include <boost/optional.hpp>
| ^~~~~~~~~~~~~~~~~~~~
compilation terminated.
See the error above. How can I compile the Crow sample code?
| You need to install Boost, for Debian that would be apt install libboost-dev.
|
71,989,160 | 71,989,211 | How to use remove_if on an std::list of structs when you want to compare to a member variable of the struct | I have an std::list of structs and I would like to remove items from the list based on if a certain member variable matches a particular value.
My struct and list:
struct Foo
{
uint64_t PID;
uintptr_t addr;
};
std::list<Foo> FooList;
Code to remove entry:
uintptr_t Bar;
FooList.remove_if(???) // Remove when "Foo.addr == Bar";
I'm not sure how to reference to the struct instance inside of the remove_if() function, any help would be appreciated!
Thanks,
Naitzirch
| list::remove_if takes a function object as its argument. You can feed with an inline lambda function like this:
FooList.remove_if([Bar] (auto &element) {
return element.addr == Bar;
});
Edit: be advised that if Bar is a local variable declared outside if the lambda, you need to capture it via copy (Bar) or reference (&Bar) within the lambda capture list (the leading square brackets)
|
71,989,237 | 71,989,363 | Deleting an item somewhere in a vector of structs | I have a vector that is filled with structs. The struct looks something like this:
struct entry{
int something
int something2;
int LRU; // least recently used
};
What I want to do is to first find the struct in the vector that has the lowest LRU. And tried doing this by:
least = vector[0].LRU;
for (entry &e : vector ) {
if (e.LRU < least)
least = e.LRU;
}
Is this something that would work? And how do I now delete the right struct in the TLB?
Thanks in advance!
| One way could be to make sure that the element with the lowest LRU is last in vector using std::nth_element. You can then just resize() vector to get rid of the last element.
Example:
if(not vector.empty()) {
std::nth_element(vector.begin(), std::prev(vector.end()), vector.end(),
[](auto&& lhs, auto&& rhs) {
return rhs.LRU < lhs.LRU;
});
vector.resize(vector.size() - 1);
}
Another way is to use std::min_element to get an iterator to the entry with the lowest LRU and then call vector.erase() with that iterator.
if(not vector.empty()) {
auto it = std::min_element(vector.begin(), vector.end(),
[](auto&& lhs, auto&& rhs) {
return lhs.LRU < rhs.LRU;
});
vector.erase(it);
}
|
71,989,520 | 71,989,967 | Creating server-socket connection without waiting for user input | My goal is to create a user-server connection. Most importantly I'm not willing to use threads.
For now, I want it to work as a simple chat. I believe The issue is that It goes from one user to another in a loop waiting for their getline input, so technically only one user can send a message at a time. What I wish is that my code could handle multiple messages from one user continuously, not having to wait for all other users to send a message
That's the running loop inside the server:
while (running)
{
fd_set copy = master;
// See who's talking to us
int socketCount = select(0, ©, nullptr, nullptr, nullptr);
// Loop through all the current connections / potential connect
for (int i = 0; i < socketCount; i++)
{
// Makes things easy for us doing this assignment
SOCKET sock = copy.fd_array[i];
// Is it an inbound communication?
if (sock == listening)
{
// Accept a new connection
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientsocket = accept(listening, (sockaddr*)&client, &clientSize);
// Add the new connection to the list of connected clients
FD_SET(clientsocket, &master);
// Send a welcome message to the connected client
string welcomeMsg = "Welcome to the Awesome Chat Server!\r\n";
send(clientsocket, welcomeMsg.c_str(), welcomeMsg.size() + 1, 0);
}
else // It's an inbound message
{
char buf[4096];
ZeroMemory(buf, 4096);
// Receive message
int bytesIn = recv(sock, buf, 4096, 0);
if (bytesIn <= 0)
{
// Drop the client
closesocket(sock);
FD_CLR(sock, &master);
}
else
{
// Send message to other clients, and definiately NOT the listening socket
for (int i = 0; i < master.fd_count; i++)
{
SOCKET outSock = master.fd_array[i];
if (outSock != listening && outSock != sock)
{
ostringstream ss;
ss << "SOCKET #" << sock << ": " << buf << "\r\n";
string strOut = ss.str();
send(outSock, strOut.c_str(), strOut.size() + 1, 0);
}
}
}
}
}
}
I belive this code should work, the issue is in my client code:
char buf[4096];
string userInput;
do
{
// Prompt the user for some text
cout << "> ";
getline(cin, userInput); //THATS THE ISSUE, IT WAITS FOR GETLINE
if (userInput.size() > 0) // Make sure the user has typed in something
{
// Send the text
int sendResult = send(sock, userInput.c_str(), userInput.size() + 1, 0);
if (sendResult != SOCKET_ERROR)
{
// Wait for response
ZeroMemory(buf, 4096);
int bytesReceived = recv(sock, buf, 4096, 0);
if (bytesReceived > 0)
{
// Echo response to console
cout << "SERVER> " << string(buf, 0, bytesReceived) << endl;
}
}
}
} while (userInput.size() > 0);
My question is if its really caused by getline and if so, how can it be fixed?
| The answer to your question is "yes," but with a big proviso: a properly designed server shouldn't care what the client is doing. You might want to look into select() or, if you anticipate a large user community, poll(). You don't want a multi-user server to depend on/wait for a single client.
|
71,989,544 | 71,990,238 | Arduino communication via COM Port isnt working | I want my Arduino to light up the LED if he reads "on" in the Serial Port.
At Serial.print(serialData); it prints out what he reads but at if (serialData == "on") it wont work.
int led1 = 9;
int led2 = 6;
String serialData;
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(9600);
Serial.setTimeout(10);
}
void loop() {
if (Serial.available() > 0){
serialData = Serial.readString();
Serial.print(serialData);
if (serialData == "on"){
analogWrite(led1, 255);
}
if (serialData == "off"){
analogWrite(led1, 0);
}
}
}
Anybody know, what I'm doing wrong?
| There are two issues in your code:
The timeout is set to 10ms. In 10ms, you can at best enter a single character. readString() will return after a single character and the read string will likely be "o", "n", "f".
When you hit the RETURN key, a carriage return and a line feed character are also transmitted ("\r\n").
The solution is to increase the timeout considerably and to use readStringUntil() to read until the newline character is discovered. This is the indication that a full word (or command) has been entered.
Additionally, the carriage return and line feed need to be trimmed off.
#include <Arduino.h>
int led1 = 9;
int led2 = 6;
String serialData;
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(9600);
Serial.setTimeout(2000);
}
void loop() {
if (Serial.available() > 0){
serialData = Serial.readStringUntil('\n');
serialData.trim();
Serial.println(serialData);
if (serialData == "on"){
analogWrite(led1, 255);
}
if (serialData == "off"){
analogWrite(led1, 0);
}
}
}
|
71,989,806 | 71,995,801 | How to open an HTML file in QtextBrowser | I have a ready-made HTML file, if it is opened through a browser, then a normal web page is displayed.
How can this HTML file be opened via the QTextBrowser widget so that structured information is also displayed in it as a web page?
I've tried something like this:
QFile file("/home/alex/data.html");
if(!file.open(QIODevice::ReadOnly))
QMessageBox::information(nullptr,"info",file.errorString());
QTextStream in(&file);
ui->textBrowser->setHtml(in.readAll());
but it didn't work out.
| There are dedicated classes to display full webpages:
https://doc.qt.io/qt-5/qtwebengine-index.html
https://doc.qt.io/qt-5/qtwebengine-webenginewidgets-simplebrowser-example.html
In your case, QTextBrowser can "only" display rich text following HTML tags.
|
71,990,309 | 71,990,577 | Why is this implementation of deleting an element from heap wrong? | Here is my implementation of deleting an element from Min Heap if the position of the element to be deleted is known:
void MinHeap::deleteKey(int i)
{
if(heap_size>0 && i<heap_size && i>=0)
{
if(heap_size==1)
heap_size--;
else
{
harr[i] = harr[heap_size-1];
heap_size--;
if(i<heap_size)
MinHeapify(i);
}
}
return ;
}
The function MinHeapify() is as follows:
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i]) smallest = l;
if (r < heap_size && harr[r] < harr[smallest]) smallest = r;
if (smallest != i) {
swap(harr[i], harr[smallest]);
MinHeapify(smallest);
}
}
The structure of MinHeap is as follows:
struct MinHeap
{
int *harr;
int capacity, heap_size;
MinHeap(int cap) {heap_size = 0; capacity = cap; harr = new int[cap];}
int extractMin();
void deleteKey(int i);
void insertKey(int k);
int parent(int i);
int left(int i);
int right(int i);
};
This implementation of delete follows the logic that we swap the element to be deleted with the last element(I've just over-written the last element onto the element to be deleted as we don't need the element to be deleted), and then decreasing the size of the heap array. We finally Minheapify the heap from the position of the deleted element(which is now occupied by the last element).
This implementation is working for some but not all test cases.
What is the error with this approach?
| Consider the following min heap:
0
/ \
4 1
/ \ / \
5 6 2 3
If you were to extract the node 5, with your current algorithm it would simply replace it with 3:
0
/ \
4 1
/ \ /
3 6 2
And since it has no children, nothing else is done. But this is not a min heap anymore, since 3 < 4, but 4 is a parent of 3.
To implement this you first need to sift-up the node, then sift-down (what you've called MinHeapify):
// Swap with parent until parent is less. Returns new index
int MinHeap::siftUp(int i)
{
while (i > 0)
{
int i_parent = parent(i);
if (harr[i_parent] < harr[i]) break;
swap(harr[i_parent], harr[i]);
i = i_parent;
}
return i;
}
// Swap with smallest child until it is smaller than both children. Returns new index
int MinHeap::siftDown(int i) {
while (true)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i]) smallest = l;
if (r < heap_size && harr[r] < harr[smallest]) smallest = r;
if (smallest == i) break;
swap(harr[i], harr[smallest]);
i = smallest;
}
return i;
}
void MinHeap::deleteKey(int i)
{
if (i<heap_size && i>=0)
{
if (i == heap_size-1)
heap_size--;
else
{
harr[i] = harr[heap_size-1];
heap_size--;
i = SiftUp(i);
SiftDown(i);
}
}
}
|
71,990,579 | 71,990,880 | correct usage of reference in a class | Here is my usage:
void fun_out(int& mkol){
mkol = 3;
}
class refTest{
public:
int pol_as;
refTest(int& poul):
pol_as(poul){}
void fun1(){
fun_out(pol_as);
}
};
int main(){
int asl = 46;
refTest testcase(asl); // testcase.pol_as = 46
testcase.fun1(); // testcase.pol_as = 3
printf("testcase.pol_as: %d\n", testcase.pol_as);
}
I need to change asl to the value in fun_out, i.e. 3 in this case; however, this code cannot do it. Only testcase.pol_as is modified from 46 to 3. Do we have a method that can change the int(asl) or a pointer value(int* asl_ptr) outside a class w.r.t. the result of a function (fun1) within this class?
|
I need to change asl to the value in fun_out
Currently you're storing a copy of asl into the data member pol_as. This means that when you call fun_out from inside fun1 it will only effect that copy. So to achieve the desired effect you can either make the data member pol_as as an lvalue reference to int or you can directly call fun_out passing asl as shown below:
Method 1
class refTest{
private:
//----v---------->lvalue reference
int &pol_as;
public:
refTest(int& poul):
pol_as(poul){}
void fun1(){
fun_out(pol_as);
}
};
Demo
Method 2
Or directly call fun_out passing asl.
int main(){
int asl = 46;
fun_out(asl);//directly pass asl
std::cout<<"asl: "<<asl;
}
Demo
|
71,990,814 | 71,990,909 | How to invoke a templated static class method having tuple input in a constexpr way | How can a static constexpr class::method (int i1, int i2, int i3) be invoked, having input data available as tuple<int, int, int> in a constexpr way.
The default approach is using std::apply to apply each tuple element as argument to a function.
A minimal example to visualize, what I try to achieve looks like:
struct a {
template <typename T>
static constexpr void test(int i1, int i2, int i3) {
// ...
}
};
struct b : a {};
struct c {};
template <typename T>
struct test_functor {
constexpr test_functor_t() {} // just for testing to express constexpr desire
constexpr void operator()(auto... args) {
T::test<c>(args...);
}
};
constexpr std::tuple<int, int, int> tupl{ 1,2,3 };
constexpr test_functor<b> f;
std::apply(f, tupl);
this works at runtime, but fails to compile constexpr. How can this be implemented?
| Working test_functor:
template <typename T>
struct test_functor {
constexpr void operator()(auto... args) const {
T::template test<c>(args...);
}
};
The problems:
Your constructor was misnamed, and ultimately unnecessary – without a constructor your type is an aggregate and can be constexpr-constructed just fine.
Your operator() was not const – the primary problem, as you can't invoke a non-const member on a constexpr object.
Missing template keyword when invoking T::test – see this FAQ answer for a good explanation of dependent names.
Online Demo
|
71,991,237 | 72,015,327 | Map QWidget center position to QGraphicsScene coordinates? | I have a QGraphicsItem with an embedded QWidget, this QWidget have a QPushButton in it.
I'm trying to map the center of the QPushButton to the QGraphicsScene coordinates, so for example, I can add a Circle to the center of the QPushButton.
With the help from another post I was able to find the center of the QPushButton, but it doesn't correspond to its actual position in the QGraphicsScene.
What I tried:
Getting the QRect of the button and then its center, finally mapping to the global coordinates of the view.
Getting the QRect of the button, then its center and mapping it to the QGraphicsItem.
Getting the QRect of the button, then its center, mapping it to the QGraphicsItem and than mapping it to the scene.
In general, I tried mapping it to Scene, to Global and to Item but it always looks incorrect. And the farther I move the QGraphicsItem, the less accurate it gets. Here the circle is supposed to be positioned at the center of the "B" button:
Qwidget:
class NodeFrame : public QFrame
{
public:
NodeFrame();
QRect getButtonRect()
{
return layout->itemAt(0)->geometry();
}
private:
QPushButton* button = nullptr;
QHBoxLayout* layout = nullptr;
};
NodeFrame::NodeFrame()
{
setFixedSize(200,80);
// Creates and add a QPushButton to the frame.
// I need the position of this button on the QGraohicsScene
button = new QPushButton("B");
button->setFixedSize(40,20);
layout = new QHBoxLayout();
layout->addWidget(button);
layout->setAlignment(Qt::AlignCenter);
setLayout(layout);
}
QGraphicsItem:
class Node : public QGraphicsItem
{
public:
Node();
QRectF boundingRect() const override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
QRect getButtonRect()
{
return frame->getButtonRect();
}
NodeFrame* frame = nullptr;
};
Node::Node()
{
setFlag(ItemIsMovable);
// Create a GraphicsProxyWidget to insert the nodeFrame into the scene
auto proxyWidget = new QGraphicsProxyWidget(this);
frame = new NodeFrame();
proxyWidget->setWidget(frame);
// Center the widget(frame) at the center of the QGraphicsItem
proxyWidget->setPos(boundingRect().center() - proxyWidget->boundingRect().center());
}
QRectF Node::boundingRect() const
{
return QRectF(-10, -10, 280, 150);
}
void Node::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
QPainterPath path;
path.addRoundedRect(boundingRect(), 10, 10);
painter->drawPath(path);
}
main:
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
// Create scene and view
auto scene = new QGraphicsScene();
auto view = new QGraphicsView(scene);
view->setMinimumSize(800, 800);
// Create the QGraphicsItem and add it to the scene
auto item = new Node();
scene->addItem(item);
item->setPos(50, 50);
auto btnRect = item->getButtonRect();
auto center = view->mapToGlobal(btnRect.center());
auto circle = new QGraphicsEllipseItem();
circle->setRect(QRectF(center.x(), center.y(), 25, 25));
scene->addItem(circle);
// Show the the view
view->show();
return app.exec();
}
Appreciate any help.
| Solved. This was caused by two things:
1: QRectF getButtonRect() was returning layout->itemAt(0)->geometry(), (index 0 being the first and only widget in the layout) but button->frameGeometry() seems to be a more accurate visual representation of the button's geometry.
2: When adding the widget to the graphic item using QGraphicsProxyWidget, I was adjusting the position of the widget inside the graphic item using:
proxyWidget->setPos(boundingRect().center() - proxyWidget->boundingRect().center());
This was changing the position (obviously) of the widget inside the graphic item, so visually it didn't align with the result given by button->frameGeometry().
|
71,991,758 | 72,336,920 | C++ filesystem lib not importing | I'm working on a small project with CMake and I'm trying to use the filesystem library to generate asset directories but when trying to use namespace fs = std::filesystem visual studio marks it with a red underline and it doesn't build correctly. I can't find any reason why this shouldn't work. The code I'm using is:
#include <filesystem>
namespace fs = std::filesystem;
| The problem is that I was not using C++ Standard >= 17
By using target_compile_features(MyTarget PRIVATE cxx_std_17) in my CMakeLists.txt suggested it fixed the issue of the <filesystem> header being empty
|
71,991,780 | 72,011,242 | ld.lld: error: could not open 'libLIBCMTD.a': No such file or directory | I recently installed vspkg and tried to build my c++ application with libcurl using command vcpkg.exe install curl:x64-windows-static
After i tried to compile it, i got an error on linking stage
ld.lld: error: could not open 'libLIBCMTD.a': No such file or directory
ld.lld: error: could not open 'libOLDNAMES.a': No such file or directory
collect2.exe: error: ld returned 1 exit status
mingw32-make[3]: *** [CMakeFiles\testEnv.dir\build.make:140: C:/Users/Administrator/libtestEnv.dll] Error 1
mingw32-make[2]: *** [CMakeFiles\Makefile2:82: CMakeFiles/testEnv.dir/all] Error 2
mingw32-make[1]: *** [CMakeFiles\Makefile2:89: CMakeFiles/testEnv.dir/rule] Error 2
mingw32-make: *** [Makefile:123: testEnv] Error 2
I also tried to install curl library non-static and everything went successfully but i want to have everything linked as one libary so it's not a good solution
My CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(testEnv)
# remove names of functions and optimize
set(CMAKE_CXX_FLAGS "-nolibc -s -O3 -Os -fdata-sections -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -fuse-ld=lld")
set(CMAKE_CXX_STANDARD 17)
find_package(CURL CONFIG REQUIRED)
add_library(testEnv SHARED main.cpp)
target_link_libraries(testEnv CURL::libcurl)
#collect all needed libraries to run
target_link_libraries(testEnv -static)
Any ideas how to fix that problem with linking? Maybe there is any solutions which would allow to exclude those problematic libs?
|
mingw32-make
looks like you are using mingw. Consider using the correct vcpkg triplet, e.g. x64-mingw-static.cmake.
x64-windows-static will use an installed VS toolchain.
Be aware that you also need to set -DVCPKG_TARGET_TRIPLET=x64-mingw-static and -DVCPKG_HOST_TRIPLET=x64-mingw-static in your cmake call. Also make sure cmake does clean configure.
|
71,991,901 | 71,992,858 | error: ISO C++ forbids converting a string constant to ‘char*’ | I'm trying to run the following code, taken from "Object Oriented Programming with C++" by Balagurusamy (8th edition):
#include <iostream>
#include <cstring>
using namespace std;
class String
{
char *name;
int length;
public:
String()
{
length = 0;
name = new char[length+1];
}
String(char *s)
{
length = strlen(s);
name = new char[length+1];
strcpy(name,s);
}
void display(void)
{cout<<name<<"\n";}
void join(String &a, String &b);
};
void String :: join(String &a, String &b)
{
length = a.length + b.length;
delete name;
name = new char[length+1];
strcpy(name, a.name);
strcat(name, b.name);
};
int main()
{
char *first = "Joseph ";
String name1(first), name2("Louis"), name3("Lagrange"), s1,s2;
s1.join(name1, name2);
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
return 0;
}
When I compile with g++, I run into the following log:
g++ -Wall -Werror -Wextra constructors_with_new.cpp -o constructors_with_new.o
constructors_with_new.cpp: In function ‘int main()’:
constructors_with_new.cpp:45:15: error: ISO C++ forbids converting a string constant to ‘char*’ [-Werror=write-strings]
45 | char *first = "Joseph ";
| ^~~~~~~~~
constructors_with_new.cpp:47:28: error: ISO C++ forbids converting a string constant to ‘char*’ [-Werror=write-strings]
47 | String name1(first), name2("Louis"), name3("Lagrange"), s1,s2;
| ^~~~~~~
constructors_with_new.cpp:47:44: error: ISO C++ forbids converting a string constant to ‘char*’ [-Werror=write-strings]
47 | String name1(first), name2("Louis"), name3("Lagrange"), s1,s2;
| ^~~~~~~~~~
cc1plus: all warnings being treated as errors
Then I found the following answer
Why is conversion from string constant to 'char*' valid in C but invalid in C++
and to make it work, I modified the above code
to receive a pointer to const char inside the 2nd constructor (String(char const *s))
inside main(), by changing the initialization of the first name "Joseph", from char * first to char const * first, as suggested by Jeremy Coffin in the answer to the provided link
In this way, it compiles without problems with the following output
Joseph
Louis
Lagrange
Joseph Louis
Joseph Louis Lagrange
What I wonder is whether this is the best way to fix this problem, or if you recommend a different way (maybe another that doesn't need to enter a pointer to a const of type char).
Best,
Stefano
| As the comments indicate, you need to use const char*, not char*. It looks like the book is badly out of date.
In C++, a string literal is of type const char[N], where N is the number of characters in the literal plus one for the terminating '\0'.
I was able to make your code compile and run by making the following changed:
Change the constructor for String from
String(char *s)
to
String(const char *s)
Change the declaration of first from
char *first = "Joseph ";
to
const char *first = "Joseph ";
Remove the extraneous semicolon at the end of String::join.
Also, the code would be a lot more legible with proper indentation.
|
71,991,995 | 71,992,253 | Cleanly exit Boost thread member of class | I have a class that has a boost::thread member variable. I have a private member function that is run in that thread (see code below).
class Human
{
public:
Human()
: m_thinkThread(&Human::think, this)
{ }
~Human()
{
m_thinkThread.interrupt();
m_thinkThread.join();
}
private:
void think()
{
// do some thinking...
}
boost::thread m_thinkThread;
};
Do I need the interrupt and join calls and therefore the custom destructor? Or will the default destructor take care of exiting cleanly? If the default destructor is all I need, then what does it do "under the hood" to ensure the thread is exited cleanly?
If I do however, need the interrupt and join calls, then my current setup has a bug because join() can throw, which will be an uncaught exception in a destructor. How would I handle this case?
Thank you
|
Do I need the interrupt and join calls and therefore the custom destructor? Or will the default destructor take care of exiting cleanly? If the default destructor is all I need, then what does it do "under the hood" to ensure the thread is exited cleanly?
Yes. There's std::jthread in more recent standard versions, which would auto-join.
If I do however, need the interrupt and join calls, then my current setup has a bug because join() can throw, which will be an uncaught exception in a destructor. How would I handle this case?
If I remember correctly there's a join_nothrow operation as well. In case that's me remembering an implementation detail, consider using a thread guard.
This seems to have been added to Boost Thread after Anthony Williams' "Concurrency In Action" (chapter 2.1.3) which seems to have never received documentation.
struct Human
{
Human() : m_thinkThread(&Human::think, this) {}
private:
void think() const;
boost::thread m_thinkThread;
boost::thread_guard<boost::interrupt_and_join_if_joinable> m_guard{m_thinkThread};
};
Live On Coliru
void Human::think() const {
while (true) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(1500));
std::cout << "Thinking..." << std::endl;
}
}
int main() {
Human plight;
boost::this_thread::sleep_for(boost::chrono::seconds(10));
}
Prints
Thinking...
Thinking...
Thinking...
Thinking...
Thinking...
Thinking...
then cleanly shuts down after 10 seconds.
Caveats
There have been versions of boost where using thread-guards in a situation with nested interruptable threads there would be unhandled exceptions: see https://github.com/boostorg/thread/issues/366
|
71,992,255 | 71,992,306 | C++ returns 0xC0000005 status | I am new to C++. In the code below, I am probably doing something wrong, because in the terminal I get Process returned -1073741819 (0xC0000005) execution time : 1.533 s
main.cpp
#include <iostream>
#include "foo.h"
int main() {
Baz* quuz;
quuz->quux();
return 0;
}
foo.h
#include <vector>
class Bar {
public:
bool boolean_val;
};
class Baz {
private:
std::vector<Bar> qux;
public:
void quux();
};
foo.cpp
#include "foo.h"
#include <iostream>
void Baz::quux()
{
qux[0].boolean_val = true;
}
Could you please highlight what I am doing wrong?
| Baz* quuz;
quuz->quux();
Calling a function on an uninizialized pointer is no bueno.
void Baz::quux()
{
qux[0].boolean_val = true;
}
Follows uninitiliazed this pointer to access qux. Undefined behavior invoked. You're lucky to get a crash. 0xC0000005 is accessed memory that is not mapped.
|
71,992,295 | 71,992,355 | Does a C++ STL Map move a value's location around after creation? | I have read some hints here and there that after inserting an object into a c++ stl map, then as long as one doesn't delete it, its location in memory never changes. But nobody ever mentioned any literature or sources to back it up, so I don't know how reliable such hints are. Can anyone answer this definately/reliably? Could it be implementation-dependent? Is there a guarantee anywhere?
|
Does a C++ STL Map move a value's location around after creation?
No.
Can anyone answer this definately/reliably?
You can rely on it.
Could it be implementation-dependent?
It couldn't be dependent on implementation.
Is there a guarantee anywhere?
Yes, it is guaranteed in the C++ standard:
[container.rev.reqmts]
Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container.
[associative.reqmts.general]
The insert, insert_range, and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
The extract members invalidate only iterators to the removed element; pointers and references to the removed element remain valid.
However, accessing the element through such pointers and references while the element is owned by a node_type is undefined behavior.
References and pointers to an element obtained while it is owned by a node_type are invalidated if the element is successfully inserted.
|
71,992,392 | 71,998,018 | Undetectable NaN when using quiet_NaN() and -Ofast | I am writing a classic nanmean function with OpenCV.
I try to emulate MatLab's nanmean by default behaviour (i.e. nanmean reduce on the first dimension).
I generate a matrix of random size which can be CV_32F or CV_64F with up to 4 channels. I fill it with random values following a uniform law.
Then I assign some values to Nan using std::numerical_limits<float> (if CV_32F, double otherwise) :: quiet_NaN();
During the debugging step I was looking for an issue and I print the following:
T v = *it_src;
std::cout<<"v before: "<<v<<" "<<std::isnan(v)<<" "<<cvIsNaN(v)<<" "<<(v==v)<<" "<<" "<<std::isinf(v)<<" "<<((v+v)==v)<<std::endl;
T is template type, it can be either float or double, nothing else.
The output is:
v before: nan 0 0 1 0 1
So the value is "nan" but neither "std::isnan" nor "CvIsNan" can detect it.
The comparison feature from IEEE 754 (if v is a Nan then v == v should be false) failed (v == v return true). The only thing that works is the last check ((v+v) == v).
I have few questions:
Simply why?
Is where this issue come from and how to fix it?
Can SIMD instructions also be concerned by this?
#include <opencv2/core.hpp>
#include <iostream>
using namespace cv;
int main()
{
// Initialization
int rows(theRNG().uniform(10,21)), cols(theRNG().uniform(10,21));
int cn(theRNG().uniform(1, 5)); // [1, 5[ -> [1,4]
Mat src(rows, cols, CV_32FC(cn));
theRNG().fill(src, RNG::UNIFORM, 0, 10000);
float ratio = theRNG().uniform(0.1f, 0.8f);
int nb_points = saturate_cast<int>(src.total() * ratio);
for(int i=0;i<nb_points;i++)
{
int x = theRNG().uniform(0, cols);
int y = theRNG().uniform(0, rows);
int z = theRNG().uniform(0, cn);
src.ptr<float>(y,x)[z] = std::numeric_limits<float>::quiet_NaN();
}
Mat dst = Mat::zeros(1, cols, src.type());
// Computation (reduce mean with omition of the Nan value over the first axis).
const size_t src_step1 = src.step1();
for(int c=0; c<cols; c++)
{
// The default constructor of Scalar_ initialize the elements of the attribute "val" to 0.
Scalar sum;
Scalar_<int> cnt;
const float* it_src = src.ptr<float>(0,c);
for(int r=0; r<rows; r++, it_src+=src_step1)
for(int i=0;i<cn;i++)
{
float v = it_src[i];
std::cout<<"v before: "<<v<<" "<<std::isnan(v)<<" "<<cvIsNaN(v)<<" "<<(v==v)<<" "<<" "<<std::isinf(v)<<" "<<((v+v)==v)<<std::endl;
if(!std::isnan(v)) // Failing
{
sum[i]+= saturate_cast<double>(v);
cnt[i]++;
}
}
for(int i=0; i<cn;i++)
{
float den = saturate_cast<float>(cnt[i]);
if(den==0.f)
den = 1.f;
dst.ptr<float>(0, c)[i] = saturate_cast<float>(sum[i]) / den;
}
}
return 0;
}
| You mention in the comments that you were using -Ofast, and this was causing the issue. To understand why this is, we start by looking at the GCC documentation for options that control optimizations. Here it lists the following options that are turned on by -Ofast:
It turns on -ffast-math, -fallow-store-data-races and the
Fortran-specific -fstack-arrays, unless -fmax-stack-var-size is
specified, and -fno-protect-parens.
For your case, looking at the description of -ffast-math seems relevant, as it sets the following set of options:
Sets the options -fno-math-errno, -funsafe-math-optimizations,
-ffinite-math-only, -fno-rounding-math, -fno-signaling-nans, -fcx-limited-range and -fexcess-precision=fast.
I didn't look at what each of all these options do, but -ffinite-math-only specifically seems like it would be incompatible with any program that cares about NaN or Inf, as it is documented as:
Allow optimizations for floating-point arithmetic that assume that
arguments and results are not NaNs or +-Infs.
This option is not turned on by any -O option since it can result in
incorrect output for programs that depend on an exact implementation
of IEEE or ISO rules/specifications for math functions. It may,
however, yield faster code for programs that do not require the
guarantees of these specifications. [emphasis added]
Since your use case clearly includes detecting NaN, it would seem ill-advised to use this flag.
Simple example program that demonstrates the issue, when compile with GCC 11.3 using the -Ofast option (Example on Godbolt because I don't have access to GCC right now). With -O3 nothing is printed as expected, and with -Ofast it prints Brought to you by -Ofast:
#include <limits>
#include <cstdio>
#include <cmath>
int main() {
auto value = std::numeric_limits<float>::quiet_NaN();
if(!std::isnan(value)) {
std::puts("Brought to you by -Ofast");
}
}
|
71,992,422 | 71,992,524 | Pass by reference to a function accepting a universal reference | I am trying to use an API which sets a value of a variable based on an HTTP call. The function in which I can set the variable which will be set upon an HTTP Call is of type T&&. I would like to access this variable on a different thread. I tried to simplify the problem and represent it in the following code, as two threads, accessing a variable the same way.
#include <iostream>
#include <thread>
#include <chrono>
class Values
{
public:
int i;
std::string s;
};
template<typename T>
void WriteCycle(T&& i)
{
using namespace std::chrono_literals;
while (true)
{
i++;
std::cout << i << std::endl;
std::this_thread::sleep_for(500ms);
}
}
template<typename T>
void ReadCycle(T&& i)
{
using namespace std::chrono_literals;
while (true)
{
std::cout << i << std::endl;
std::this_thread::sleep_for(500ms);
}
}
int main() {
auto v = new Values();
std::thread t1(WriteCycle<int>, v->i);
std::thread t2(ReadCycle<int>, v->i);
t1.join();
t2.join();
}
Currently the read thread does not see any change in the variable. I read up an perfect forwarding, move semnatics and forwardin references, but I did not get it (I mostly program dotnet, my c++ knowledge is pre C++11). I tried all combinations of std::move, std::ref and std::forward but I cannot get the read thread to see the change of the write thread. Is there a way to solve this, without changing the T&& input type of the functions (since that is part of the API I am trying to use)? How to solve this in a thread-safe way?
| Such notation:
template<typename T>
void WriteCycle(T&& i)
Doesn't really mean an rvalue reference, it means a universal reference, which could be an lvalue reference or rvalue reference depending on what kind of data you pass.
In your case it turns into just an lvalue reference, so it has nothing to do with move semantic. The problem is that thread constructor is not quite friendly with references and you may want just to use std::ref to get it round:
auto myRef = std::ref(v->i);
std::thread t1(WriteCycle<&int>, myRef);
std::thread t2(ReadCycle<&int>, myRef);
However it still won't be perfect, because you want to synchronize between threads with use of mutexes or atomic values
|
71,994,048 | 71,994,272 | Is direct-initialization equivalent to direct-list-initialization? | I have the following example:
struct S{
int x, y;
}
S s1{1}; // direct-initialization or direct-list-initialization ?
S s2{1, 2}; // direct-initialization or direct-list-initialization ?
S s3(1); // direct-initialization or direct-list-initialization ?
S s4(1, 2); // direct-initialization or direct-list-initialization ?
int i1{10}; // direct-initialization or direct-list-initialization ?
int i2(10); // direct-initialization or direct-list-initialization ?
My questions
I just need to know what's the type of initialization in the above statements?
Is there any standard quote applied here?
I am already checked the question direct-initialization vs direct-list-initialization (C++), but it hasn't strict answer yet.
| From direct initialization's documentation:
T object ( arg );
T object ( arg1, arg2, ... );
(1)
T object { arg }; (2) (since C++11)
T ( other )
T ( arg1, arg2, ... )
(3)
Direct initialization is performed in the following situations:
initialization with a nonempty parenthesized list of expressions or braced-init-lists (since C++11)
initialization of an object of non-class type with a single brace-enclosed initializer (note: for class types and other uses of braced-init-list, see list-initialization)
initialization of a prvalue temporary (until C++17)the result object of a prvalue (since C++17) by functional cast or with a parenthesized expression list
And from List initialization:
Direct-list-initialization
T object { arg1, arg2, ... }; (1)
T { arg1, arg2, ... } (2)
Now we can use the above to answer your question.
S s1{1}; // direct-list-initialization from direct-list init point 1 above
S s2{1, 2}; // direct-list-initialization from direct-list init point 1 above
S s3(1); // direct-initialization from direct init point 1 above
S s4(1, 2); // direct-initialization from direct init point 1 above
int i1{10}; // direct-initialization from direct init point 2 above
int i2(10); // direct-initialization from direct init point 1 above
|
71,994,108 | 71,994,361 | Why string shown up in Shared Library file like .so file in Linux? | May I know why the .so file in linux will show up the string value from my cpp code? Even with fvisibility=hidden set in gcc make.
for example, i set "Hello World" and it will show up.
I tried google but found nothing related..
Thanks.
| -fvisibility=hidden only affects the linker visibility, i.e. whether symbols are visible when a linker tries to link against your file. It does not specify any active obfuscation.
Your strings are still placed inside a data section and need to be loaded into the memory space of the process when your library is loaded, so they will still need to be visible when inspecting the file. If you need them to be obfuscated, you will need to obfuscate them yourself and decode them at runtime (knowing that a sufficiently determined attacker can still reverse engineer or debug your library).
|
71,994,237 | 71,994,424 | Passing 2D arrays as argument to a function and get another 2D array | I'm writing a code which calculates the inverse matrix given a matrix, the thing is, I need that to be included in other code that makes statistical fits, so I need something like a function that receives the size of the matrix (matrix is square matrix) and the matrix itself and returns his inverse, I found something about the syntax and then have this (Gauss-Jordan)
float* inv(int n, float *A)
{
float* I = 0;//*
float aux;
float pivote;
for(int i = 0; i<n; i++){
for(int j = 0; j<n; j++){
if(i == j)
{
*(I+i*n+j) = 1.0; //*
}
else {
*(I+i*n+j) = 0.0;
}
}
}
for(int i = 0; i<n; i++)
{
pivote = *(A+i*n+i);
for(int k = 0; k<n; k++)
{
*(A+i*n+k) = *(A+i*n+k)/pivote;//*
*(I+i*n+k) = *(I+i*n+k)/pivote;//*
}
for(int j = 0; j<n; j++)
{
if(i!=j)
{
aux = *(A+j*n+i);//*
for(int k = 0; k<n;k++)
{
*(A+j*n+k)=*(A+j*n+k)-aux**(A+i*n+k);//*
*(I+j*n+k)=*(I+j*n+k)-aux**(I+i*n+k);//*
}
}
}
}
return I;//*
}
There where I put the //* is where I have my doubts, is the syntax correct? the declarations, there in the return should be something else than just I?. When I compile I get a segmentation fault, Following Taekahn recommendations, compiling with sanitizers g++ -fsanitize=address -fsanitize=undefined -fsanitize=leak inverse.cpp I get
inverse.cpp:148:28: runtime error: store to null pointer of type 'float'
AddressSanitizer:DEADLYSIGNAL
=================================================================
==11993==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x00000040338c bp 0x7ffdd6a14510 sp 0x7ffdd6a144b0 T0)
==11993==The signal is caused by a WRITE memory access.
==11993==Hint: address points to the zero page.
#0 0x40338b in inv(int, float*) (/home/live/med_elect/a.out+0x40338b)
#1 0x402f30 in main (/home/live/med_elect/a.out+0x402f30)
#2 0x7f90ffed9e5a in __libc_start_main (/lib64/libc.so.6+0x23e5a)
#3 0x402289 in _start (/home/live/med_elect/a.out+0x402289)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (/home/live/med_elect/a.out+0x40338b) in inv(int, float*)
==11993==ABORTING
I really appreciate if you can help me, thank you very much in advance and thank you very much for the feedback in the comments, I'm new here with the questions.
UPDATE: Thanks to nasy for the answer, It is important to note that many people mentioned the vector approach, so, to anyone reading this, check the comments and better try the vector approach.
| In your second function, you have float *I = 0. Later on, you try to write to this array but you have not allocated it. The way you're indexing your matrices is the flattening approach so you must write float *I = new float[n*n]. There are different approaches, of course, like using dynamic 2D arrays, 2D vectors, etc. as mentioned in the comments.
|
71,994,464 | 71,994,534 | I need to choose random function in C++ project | I am making a C++ game-project and in the game I need to choose random bonuses (functions).
(below is the example of the code)
void triple_balls(){
/* CODE */
}
void longer_paddle(){
/* CODE */
}
void shorter_paddle(){
/* CODE */
}
void bonus_activator(){
//Here I must choose one of the 3 functions above
//FIXME
}
| You can use std::function, to store you functions in a container.
Then create an array of std::function of size 3.
#include <functional>
#include <iostream>
void triple_balls() { /* YOUR CODE */ }
void longer_paddle() { /* YOUR CODE */ }
void shorter_paddle() { /* YOUR CODE */ }
void bonus_activator(){
std::function<void(void)> farr[3] =
{
triple_balls,
longer_paddle,
shorter_paddle
};
farr[rand() % 3]();
}
|
71,994,867 | 71,995,031 | C++ std::string::at() | I want to print the first letter of a string.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "다람쥐 헌 쳇바퀴 돌고파.";
cout << str.at(0) << endl;
}
I want '다' to be printed like java, but '?' is printed.
How can I fix it?
| That text you have in str -- how is it encoded?
Unfortunately, you need to know that to get the first "character". The std::string class only deals with bytes. How bytes turn into characters is a rather large topic.
The magic word you are probably looking for is UTF-8. See here for more infomation: How do I properly use std::string on UTF-8 in C++?
If you want to go down this road yourself, look here: Extract (first) UTF-8 character from a std::string
And if you're really interested, here's an hour-long video that is actually a great explanation of text encoding: https://www.youtube.com/watch?v=_mZBa3sqTrI
|
71,994,899 | 71,995,520 | How to append to a std::fstream after you got to the end (std::fstream::eof() is true) | I open a file like this (Because it's part of an exercise and it may require overwriting the file):
#include <fstream> //std::fstream.
std::fstream file("file.txt", std::ios::in | std::ios::out);
And let's say I have read a file until the end (To get to the end of the file).
std::string tmp_buff;
while(std::getline(file, tmp_buff)) {}
file.seekp(file.tellg());
Now I have got to the end of the stream, How do I append to the file from here. Because if I just try to write like regularly, it will fail (It will not actually write):
file << "Text";
The only solution I have found is to reopen the file at the end of the file:
if(file.eof())
{
file.close();
file.open("file.txt", std::ios::in | std::ios::out | std::ios::app);
file << '\n';
}
Any help would be appreciated.
| First, there is no need to state std::ios::in and std::ios::out when using a fstream because they are there the default value in the constructor. (it is actually std::ios_base::in/out to be more exact. std::ios (std::basic_ios<char>) inherits from std::ios_base)
So std::fstream file(filename) works the same.
The problem here is how C++ streams work.
When the file is read completely, the eofbit is set. After that, another reading happens which will trigger the failbit because there is nothing to read and the stream's bool conversion operator returns false and it exits the loop.
The bits will stay on until they are cleared. And while they are on, the stream doesn't do anything.
So to clear them:
file.clear();
Will do the work. You can use the stream after that.
|
71,994,929 | 71,996,544 | what is the time complexity and space complexity of this solution? Question- Top K Frequent Elements (Leetcode-Medium) | vector<int> topKFrequent(vector<int>& nums, int k) {
if(k==nums.size())
return nums;
map<int,int> mp;
for(int i=0;i<nums.size();i++)
mp[nums[i]]++;
multimap<int,int> m;
for(auto& it:mp){
m.insert({it.second,it.first});
}
vector<int> ans;
for (auto itr = m.crbegin(); itr != m.crend(); ++itr){
ans.push_back(itr->second);
if(ans.size()==k)
break;
}
return ans;
}
I am using multimap to sort the map by values.I don't understand if I use priority queue which time complexity is better ? using priority_queue or using multimap? Can anyone explain?
| In my opinion you have not the optimal solution.
You use a std::map instead of a std::unordered_map. That will have a higher complexity in most cases. std::maphas logarithmic complexity, std::unordered_map has on average constant-time complexity.
The std::multimap is not needed at all. It will add unneccessary space and time complexity (Logarithmic). A std::priority_queuehas constant time lookup, but logarithmic insertion. So, could be better than the std::multimapin your case.
The most efficient solution would be to use a std::unordered_map and then std::partial_sort_copy. The complexity for this is O(N·log(min(D,N)), where N = std::distance(first, last), D = std::distance(d_first, d_last) applications of cmp. (Taken from CPPReference).
A somehow generic C++17 example solution could be the below:
#include <iostream>
#include <utility>
#include <unordered_map>
#include <algorithm>
#include <vector>
#include <iterator>
#include <type_traits>
// Helper for type trait We want to identify an iterable container ----------------------------------------------------
template <typename Container>
auto isIterableHelper(int) -> decltype (
std::begin(std::declval<Container&>()) != std::end(std::declval<Container&>()), // begin/end and operator !=
++std::declval<decltype(std::begin(std::declval<Container&>()))&>(), // operator ++
void(*std::begin(std::declval<Container&>())), // operator*
void(), // Handle potential operator ,
std::true_type{});
template <typename T>
std::false_type isIterableHelper(...);
// The type trait -----------------------------------------------------------------------------------------------------
template <typename Container>
using is_iterable = decltype(isIterableHelper<Container>(0));
// Some Alias names for later easier reading --------------------------------------------------------------------------
template <typename Container>
using ValueType = std::decay_t<decltype(*std::begin(std::declval<Container&>()))>;
template <typename Container>
using Pair = std::pair<ValueType<Container>, size_t>;
template <typename Container>
using Counter = std::unordered_map<ValueType<Container>, size_t>;
// Function to get the k most frequent elements used in any Container ------------------------------------------------
template <class Container>
auto topKFrequent(const Container& data, size_t k) {
if constexpr (is_iterable<Container>::value) {
// Count all occurences of data
Counter<Container> counter{};
for (const auto& d : data) counter[d]++;
// For storing the top k
std::vector<Pair<Container>> top(k);
// Get top k
std::partial_sort_copy(counter.begin(), counter.end(), top.begin(), top.end(),
[](const Pair<Container>& p1, const Pair<Container>& p2) { return p1.second > p2.second; });
return top;
}
else
return data;
}
int main() {
std::vector testVector{ 1,2,2,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,6,7 };
for (const auto& p : topKFrequent(testVector, 2)) std::cout << "Value: " << p.first << " \t Count: " << p.second << '\n';
std::cout << '\n';
double cStyleArray[] = { 1.1, 2.2, 2.2, 3.3, 3.3, 3.3 };
for (const auto& p : topKFrequent(cStyleArray, 2)) std::cout << "Value: " << p.first << " \t Count: " << p.second << '\n';
std::cout << '\n';
std::string s{ "abbcccddddeeeeeffffffggggggg" };
for (const auto& p : topKFrequent(s, 2)) std::cout << "Value: " << p.first << " \t Count: " << p.second << '\n';
std::cout << '\n';
double value = 12.34;
std::cout << topKFrequent(value, 2) << "\n";
}
|
71,995,309 | 72,010,801 | qml does not accept keyboard event until i switch windows | I am developing some kind of a video player in QML. I want to control it by Keyboard events but the problem is that the qml doesn't seem to accept any keyboard event until I switch the window and comeback to the app window. I tried with
"focus: true"
"enabled : true"
and
"FocusScope: Item"
but nothing worked for me
| I solved this problem by tracing the focus. The problem was during the frame/page switches I lost the focus. Hence I enabled it on each frame by forceActiveFocus.
|
71,995,672 | 71,996,403 | Strange freezing cases of Qt GUI event loop on Windows | I try to ask here if somebody has encountered such a problem.
From time to time, I have a situation: I launch my Qt app on Windows (in debug mode, but I am not sure if it matters) via cmd.exe and then I work with it and then I stop working with it for some time. Then I return it to be focused and very rarely I experience this: the app is Not Responding even though I do not have any logic for it to react on being returned to be focused. Then I wait and wait and noting happens and then I press any key in my cmd.exe, and instead of being killed, my app suddenly wakes up and continues to work, and then I do not experience any problems anymore.
What can be the problem? On Linux I do not experience such a problem. I ask because I cannot trace the problem, as it happens not very often. Also, I am not very good acquainted with Windows. If it was Linux I would use gdp -p and try to see where the app hangs. But what can I do on Windows? Any advice on how to catch this?
UPDATE: I can press any key in my cmd.exe to unfreeze the program.
UPDATE:
It looks like it freezes on one of my debug-printfs:
STACK_TEXT:
: ntdll!NtWriteFile+0x14
: KERNELBASE!WriteFile+0x76
!write_text_ansi_nolock+0x183
!_write_nolock+0x451
!_write_internal+0x377
!__acrt_stdio_flush_nolock+0xc4
!__acrt_stdio_end_temporary_buffering_nolock+0x54
!__acrt_stdio_temporary_buffering_guard::~__acrt_stdio_temporary_buffering_guard+0x28
!<lambda_303760bc4008a2b3ec4768a30b06a80c>::operator()+0x104
!__crt_seh_guarded_call<int>::operator()<<lambda_d854c62834386a3b23916ad6dae2782d>,<lambda_303760bc4008a2b3ec4768a30b06a80c> &,<lambda_4780a7ea4f8cbd2590aec34bd14e2bbf> >+0x35
!__acrt_lock_stream_and_call<<lambda_303760bc4008a2b3ec4768a30b06a80c> >+0x58
!common_vfprintf<__crt_stdio_output::standard_base,char>+0x21a
!__stdio_common_vfprintf+0x5c
!_vfprintf_l+0x3f
!printf+0x58
! MyClass::myfunc -- that executes my handler of the button pressed (which freezes)
Why can be so? I mean it's just a printf writing to cmd.
| Here is the answer to my question:
https://stackoverflow.com/a/33883532/4781940
I really have that Select Command Prompt title when the freeze happens.
|
71,995,707 | 72,031,746 | How to use reflection of Protobuf to modify a Map | I'm working with Protobuf3 in my C++14 project. There have been some functions, which returns the google::protobuf::Message*s as a rpc request, what I need to do is to set their fields. So I need to use the reflection of Protobuf3.
Here is a proto file:
syntax="proto3";
package srv.user;
option cc_generic_services = true;
message BatchGetUserInfosRequest {
uint64 my_uid = 1;
repeated uint64 peer_uids = 2;
map<string, string> infos = 3;
}
message BatchGetUserInfosResponse {
uint64 my_uid = 1;
string info = 2;
}
Service UserSrv {
rpc BatchGetUserInfos(BatchGetUserInfosRequest) returns (BatchGetUserInfosResponse);
};
Now I called a function, which returns a google::protobuf::Message*, pointing an object BatchGetUserInfosRequest and I try to set its fields.
// msg is a Message*, pointing to an object of BatchGetUserInfosRequest
auto descriptor = msg->GetDescriptor();
auto reflection = msg->GetReflection();
auto field = descriptor->FindFieldByName("my_uid");
reflection->SetUInt64(msg, field, 1234);
auto field2 = descriptor->FindFieldByName("peer_uids");
reflection->GetMutableRepeatedFieldRef<uint64_t>(msg, field2).CopyFrom(peerUids); // peerUids is a std::vector<uint64_t>
As you see, I can set my_uid and peer_uids as above, but for the field infos, which is a google::protobuf::Map, I don't know how to set it with the reflection mechanism.
| If you dig deep into the source code, you would find out the map in proto3 is implemented on the RepeatedField:
// Whether the message is an automatically generated map entry type for the
// maps field.
//
// For maps fields:
// map<KeyType, ValueType> map_field = 1;
// The parsed descriptor looks like:
// message MapFieldEntry {
// option map_entry = true;
// optional KeyType key = 1;
// optional ValueType value = 2;
// }
// repeated MapFieldEntry map_field = 1;
//
// Implementations may choose not to generate the map_entry=true message, but
// use a native map in the target language to hold the keys and values.
// The reflection APIs in such implementations still need to work as
// if the field is a repeated message field.
//
// NOTE: Do not set the option in .proto files. Always use the maps syntax
// instead. The option should only be implicitly set by the proto compiler
// parser.
optional bool map_entry = 7;
Inspired by the test code from protobuf, this works for me:
BatchGetUserInfosRequest message;
auto *descriptor = message.GetDescriptor();
auto *reflection = message.GetReflection();
const google::protobuf::FieldDescriptor *fd_map_string_string =
descriptor->FindFieldByName("infos");
const google::protobuf::FieldDescriptor *fd_map_string_string_key =
fd_map_string_string->message_type()->map_key();
const google::protobuf::FieldDescriptor *fd_map_string_string_value =
fd_map_string_string->message_type()->map_value();
const google::protobuf::MutableRepeatedFieldRef<google::protobuf::Message>
mmf_string_string =
reflection->GetMutableRepeatedFieldRef<google::protobuf::Message>(
&message, fd_map_string_string);
std::unique_ptr<google::protobuf::Message> entry_string_string(
google::protobuf::MessageFactory::generated_factory()
->GetPrototype(fd_map_string_string->message_type())
->New(message.GetArena()));
entry_string_string->GetReflection()->SetString(
entry_string_string.get(), fd_map_string_string->message_type()->field(0),
"1234");
entry_string_string->GetReflection()->SetString(
entry_string_string.get(), fd_map_string_string->message_type()->field(1),
std::to_string(10));
mmf_string_string.Add(*entry_string_string);
std::cout << "1234: " << message.infos().at("1234") << '\n';
The output:
1234: 10
|
71,996,018 | 71,996,030 | Can I access a non-type template class argument from outside? How? | Please check the following code:
#include <iostream>
template <int Size>
class Test
{
public:
// Will not compile, if Size is not a type!
// error: 'Size' does not name a type
using MySize = Size;
double array[Size];
};
using MyTestArray = Test<3>;
int main()
{
MyTestArray testArray;
std::cout << "Test array has size " << MyTestArray::MySize << std::endl;
return 0;
}
Is there any possibility to access Size from outside without introducing a boilerplate getter like this?
constexpr static int getSize()
{
return Size;
}
| You can define a constexpr static variable with the value of the template parameter inside the class, for example
template <int Size>
class Test
{
public:
constexpr static auto MySize = Size;
double array[Size];
};
Then you access like this
using MyTestArray = Test<3>;
auto size = MyTestArray::MySize;
|
71,996,519 | 71,996,625 | Refactoring : delegate friendship in sub-functions | I refactor a code where a class has a friend function doing a lot of stuff.
class Foo
{
friend void do_something(Foo& foo);
};
void do_something(Foo& foo)
{
// More than 2000 lines of ugly code
}
I would like to split the content of do_something in several small functions. Something looking like this :
void do_something(Foo& foo)
{
if(case_1) do_1(foo);
else if(case_2) do_2(foo);
else if(case_3) do_3(foo);
//...
}
Is there a design where I can transfert the friendship to the sub-fuctions do_x(Foo&) without having to declare them in the class, or something similar in order to split the code ?
Note : C++11 only
Note : I don't want to write the sub-functions as maccros
| Instead of having do_something as function calling other sub-functions, I would suggest you to create an analogous class DoSomehting.
Then you could declare this class as a friend with friend class DoSomehting;. So these sub-functions could be its private methods. The method to call -- could be a public method named e.g. like void DoSomehting::process(Foo& foo):
class Foo
{
friend class DoSomething;
};
class DoSomething
{
public:
void process(Foo& foo)
{
if(case_1) do_1(foo);
else if(case_2) do_2(foo);
else if(case_3) do_3(foo);
//...
}
private:
void do_1(Foo& foo);
void do_2(Foo& foo);
void do_3(Foo& foo);
};
|
71,996,867 | 71,996,937 | iterator to a vector of vector of int | I have an error in the following code where I want to print the first element in each sub-vector:
vector<vector<int>> logs{{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
for (auto beg = logs.begin(); beg != logs.end(); beg++) {
cout << *beg[0] << endl;
}
the error is from cout << *beg[0]...:
Indirection requires pointer operand ('std::vector<int, std::allocator<int>>' invalid)
So my question is: the dreference of the iterator should a sub-vector in the vector "logs", so I use subscript to access the first element of it. Why there's a std::vector<int, std::allocator<int>> object? Where does the std::allocator<int> come from? How can I access the elements in the sub-vectors?
| The problem(cause of the mentioned error) is that due to operator precedence, the expression *beg[0] is grouped as(or equivalent to):
*(beg[0])
which can't work because beg is an iterator and has no [] operator. This is because the operator [] has higher precedence than operator *.
To solve this replace cout << *beg[0] << endl; with:
cout << (*beg)[0] << endl; //or use beg->at(0)
Demo
|
71,997,062 | 71,998,751 | C++ Windows function "LockResource()" returns half the data in the resource | I am trying to read an embedded resource from a dll, it contains an encrypted file. Reading it from LockResource() , only returns half the data.
The funny thing is that I checked SizeOfResource() and the size of the resource is what it is supposed to be.
So I tried to access the file without it being an embedded resource :
std::ifstream enc("Logs.enc" , std::ios::binary); // Accessing encrypted file
std::string ciphertext = std::string((std::istreambuf_iterator<char>(enc)), std::istreambuf_iterator<char>());
int size = ciphertext.size(); // Returns the correct size
This worked , I tried to find something they have in common and I tried to remove the std::ios::binary and it had similar behavior to when accessing the file as a resource.
Here is my attempt to Access it as a resource :
HGLOBAL SHEET_DATA; // Imagine this has the encrypted file
if (SHEET_DATA) {
char* datac = nullptr;
datac = (char*)LockResource(SHEET_DATA);
std::string data = datac;
long size_sheet = SizeofResource(dll, SHEET); //
int real_size = data.size(); // Returns the wrong size
}
I tried to search if there was anything such as a LockResource() function that accessess the data in binary mode , but I couldn't find any results.
Thank you
| strlen is assuming the parameter is a zero terminated string. It counts the chars until it gets to the zero termination.
In your case it seems like the resource is binary. In this case it may contain bytes with the value 0, which strlen treats as the end of the string.
Therefore what strlen returns is irrelevant. You can use size_sheet returned from SizeofResource to know the size of the data pointed by datac.
Update:
The updated question does not contain a usage of strlen anymore. But the line:
std::string data = datac;
Create a similar problem. Initializing an std::string from a char* assumes the char* is pointing to a zero terminated string. So if the buffer contains zeroes the resulting string will contain only the characters till the first zero.
You can initialize the std::string the following way to avoid the assumption of the zero termination:
std::string data(datac, size_sheet);
Giving the length of the buffer to the ctor of std::string will force initializing with the complete buffer (ignoring the zeroes).
Update2: As @IInspectable commented below, if the data is not really a string, better hold it in a more suitable container - e.g. std::vector<char>. It also has a constructor accepting a char* and the buffer's length.
|
71,997,200 | 71,998,137 | Why does Apple Clang make a call to compare for a unique hash in an unordered map? | I was trying to improve my understanding of the implementation of unordered_map
and was surprised by this behavior. Consider this minimal example below.
#include <iostream>
#include <unordered_map>
using namespace std;
template<>
struct std::hash<int*>
{
size_t operator()(int* arr) const
{
cout << "custom hash called" << endl;
return arr[0];
}
};
template <>
struct std::equal_to<int*>
{
bool operator()(const int* lhs, const int* rhs) const
{
std::cout << "call to compare" << std::endl;
return lhs == rhs;
}
};
int main(int argc, char *argv[])
{
int arr1[8] {11,12,13,14,15,16,17,18};
int arr2[8] {1,2,3,4,5,6,7,8};
unordered_map<int*, string> myMap;
myMap.insert(make_pair(arr1, "one"));
myMap.insert({arr2, "two"});
}
I would have expected this output:
custom hash called
custom hash called
The hash for both inserts is unique and therefore no comparison of multiple keys should be required as I understand it (since the bucket should only contain exactly one key). And indeed this is the result when I try it with Clang, GCC and MSVC on godbolt.org. However, when I compile and run this example on a local Mac an additional call to the equal_to call operator happens for the second insert:
custom hash called
custom hash called
call to compare
Tested with
Apple clang version 13.1.6 (clang-1316.0.21.2)
Target: arm64-apple-darwin21.4.0
Thread model: posix
and
Apple clang version 13.1.6 (clang-1316.0.21.2.3)
Target: x86_64-apple-darwin21.4.0
Thread model: posix
In all cases only the C++20 flag was used.
| There are basically two cases where the comparator does not need to be applied:
The first one is when the target bucket is empty (then, there is nothing to compare with). A simple demo code that works with both libstdc++ and libc++ is as follows:
struct Hash {
size_t operator()(int a) const { return a; }
};
struct Equal { ... /* log operator call */ };
std::unordered_map<int, int, Hash, Equal> m;
m.reserve(2);
std::cout << m.bucket(0) << std::endl; // 0
std::cout << m.bucket(1) << std::endl; // 1
m.insert({0, 0});
m.insert({1, 0})
Here, both keys 0 and 1 target different buckets, so there is no comparison with both implementations.
Live demo: https://godbolt.org/z/5jfYv6sba
The second case is when all the keys in the target bucket have different hashes and those hashes are stored (cached) in the hash table nodes. This caching is supported by libstdc++ and seems to be applied by default. However, it does not seem to be supported by libc++. Exemplary code:
std::unordered_map<int, int, Hash, Equal> m;
m.reserve(2);
std::cout << m.bucket(0) << std::endl; // 0
std::cout << m.bucket(2) << std::endl; // 0
m.insert({0, 0});
m.insert({2, 0})
Here, both keys target the same bucket (with index 0). With libstdc++, since the hashes are cached and are different, they are compared and there is no reason to additionally compare the entire keys. However, with libc++, hashes are not cached and the keys need to be compared.
Live demo: https://godbolt.org/z/vWK4Ko7Yj
|
71,997,445 | 71,997,488 | Why we must overloading += and -= beside just overloading + and - operator? | In c++, why we must overloading +=, -=, +, - operator beside just overloading + and - operator? Here is an example:
In C++, when I create a Point class, I will do:
class Point {
public:
int x, y;
public:
Point(int X, int Y) : x(X), y(Y) {}
//Assignment operator
void operator=(Point a) { x = a.x; y = a.y; }
//The += and -= operator, this seem problematic for me.
void operator+=(Point a) { x += a.x; y += a.y; }
void operator-=(Point a) { x -= a.x; y -= a.y; }
//The + and - operator
Point operator+(Point a) { return Point(x + a.x, y + a.y); }
Point operator-(Point a) { return Point(x - a.x, y - a.y); }
};
But in some other language like C# for example, we don't need to overloading the += and -= operator:
public class Point {
public int x, y;
public Point(int X, int Y) {
x = X; y = Y;
}
//We don't need to overloading =, += and -= operator in C#, all I need to do is overload + and - operator
public static Point operator+(Point a, Point b) { return Point(a.x + b.x, a.y + b.y); }
public static Point operator-(Point a, Point b) { return Point(a.x - b.x, a.y - b.y); }
}
And both will work same as c++!
So I already know that if we overloading like c++, we can easier control which operator this class can have. But what else it can do?
I'm also new in c++ and I just learn overloading operator today.
| The typical operator+= is more efficient than a = a + b, and cannot be implemented in terms of operator+. It can be the other way around though:
struct foo {
int value = 42;
foo& operator+=(const foo& other) {
this.value += other.value;
return *this;
}
foo operator+(const foo& other) const {
foo result = *this;
result += other; // reuse operator+=
return result;
}
};
Note how operator+ must create a new instance, while operator+= merely adds member of already existing instances.
In general operator+= can do something else entirely and might not be related to operator+ at all.
The same holds for operator-= vs operator-.
|
71,997,744 | 71,998,139 | How can I propagate const when returning a std::vector<int*> from a const method? | Lets show it in an example where we have a Data class with primary data, some kind of index that points to the primary data, and we also need to expose a const version the index.
class Data
{
public:
const std::vector<int>& getPrimaryData() const { return this->primaryData; }
const std::vector<int*>& getIndex() const { return this->index; }
private:
std::vector<int> primaryData;
std::vector<int*> index;
};
This is wrong, as the user can easily modify the data:
const Data& data = something.getData();
const std::vector<int*>& index = data.getIndex();
*index[0] = 5; // oups we are modifying data of const object, this is wrong
The reason of this is, that the proper type the Data::getIndex should be returning is:
const std::vector<const int*>&
But you can guess what happens when you try to write the method that way to "just convert the non-const variant to const variant":
// compiler error, can't convert std::vector<int*> to std::vector<const int*> these are unrelated types.
const std::vector<const int*>& getIndex() const { return this->index; }
As far as I know, C++ doesn't have any good solution to this problem. Obviously, I could just create new vector, copy the values from the index and return it, but that doesn't make any sense from the performance perspective.
Please, note that this is just simplified example of real problems in bigger programs. int could be a bigger object (Book lets say), and index could be index of books of some sort. And the Data might need to use the index to modify the book, but at the same time, provide the index to read the books in a const way.
| You're asking for std::experimental::propagate_const. But since it is an experimental feature, there is no guarantee that any specific toolchain is shipped with an implementation. You may consider implementing your own. There is an MIT licensed implementation, however. After including the header:
using namespace xpr=std::experimental;
///...
std::vector<xpr::propagate_const<int*>> my_ptr_vec;
Note however that raw pointer is considered evil so you may need to use std::unique_ptr or std::shared_ptr. propagate_const is supposed to accept smart pointers as well as raw pointer types.
|
71,997,768 | 72,159,778 | Mesh getting cut off | I'm using DirectX 11. I'm trying to draw a Cube mesh to the screen but the bottom half is getting cut off. If I move the camera up/down the bottom half is still cut off, which leads me to think that it's not a viewport/rasterizer issue, but I'm not sure. The pictures are of the cube looking down and then looking up. You can see the cube is getting cut off regardless of the camera position. I think it might be an issue with my projection matrices.
I've attached the RenderDoc capture here, and you can see that the VS input is correct, but when viewing the VS output with solid shading, the same thing happens. https://drive.google.com/file/d/1sh7tj0hPYwD936BEQCL0wtH8ZzXMiEno/view?usp=sharing
This is how I'm calculating my matrices:
mat4 LookAtMatrix(float3 Position, float3 Target, float3 Up) {
float3 Forward = Normalise(Target - Position);
float3 Right = Cross(Normalise(Up), Forward);
float3 UpV = Cross(Forward, Right);
mat4 Out;
Out.v[0] = float4(Right, 0);
Out.v[1] = float4(UpV, 0);
Out.v[2] = float4(Forward, 0);
Out.v[3] = float4(Position, 1);
return Out;
}
mat4 ProjectionMatrix(f32 FOV, f32 Aspect, f32 Near, f32 Far) {
mat4 Out;
f32 YScale = 1.0f / tan((FOV * Deg2Rad) / 2.0f);
f32 XScale = YScale / Aspect;
f32 NmF = Near - Far;
Out.v[0] = float4(XScale, 0, 0, 0);
Out.v[1] = float4(0, YScale, 0, 0);
Out.v[2] = float4(0, 0, (Far + Near) / NmF, -1.0f);
Out.v[3] = float4(0, 0, 2 * Far * Near / NmF, 0);
return Out;
}
And this is how I'm calling these functions (The issue happens reguardless of whether I use rotation or not):
D3D11_MAPPED_SUBRESOURCE Resource;
HRESULT Result = DeviceContext->Map(ConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &Resource);
if(FAILED(Result)) FatalError("DeviceContext->Map failed");
matrix_buffer *Buffer = (matrix_buffer *)Resource.pData;
static float yR = 0.0f;
yR += 50.0f * DeltaTime;
while(yR > 360.0f) yR -= 360.0f;
while(yR < 0.0f) yR += 360.0f;
quat R = QuatFromAngles(0.0f, yR, 0.0f);
const float Speed = 100.0f;
static float3 Position = float3(0, 0, -300);
if(WDown) Position.z += Speed * DeltaTime;
if(ADown) Position.x += Speed * DeltaTime;
if(SDown) Position.z -= Speed * DeltaTime;
if(DDown) Position.x -= Speed * DeltaTime;
if(QDown) Position.y -= Speed * DeltaTime;
if(EDown) Position.y += Speed * DeltaTime;
Buffer->WorldMatrix = RotationMatrix(R, float3(0, 0, 0));
Buffer->ViewMatrix = LookAtMatrix(Position, Position+float3(0, 0, 1), float3(0, 1, 0));
Buffer->ProjectionMatrix = ProjectionMatrix(45.0f, 1366/768, 0.1f, 1000.0f);
DeviceContext->Unmap(ConstantBuffer, 0);
And this is my vertex shader code:
struct vertex_data {
float3 Position : POSITION;
float2 UV : TEXCOORD;
float4 Colour : COLOR;
float3 Normal : NORMAL;
};
struct pixel_data {
float4 Position : SV_POSITION;
float2 UV : TEXCOORD;
float4 Colour : COLOR;
float3 Normal : NORMAL;
};
cbuffer MatrixBuffer {
float4x4 WorldMatrix;
float4x4 ViewMatrix;
float4x4 ProjectionMatrix;
};
pixel_data VertexMain(vertex_data Input) {
pixel_data Output;
float4 V = float4(Input.Position, 1);
Output.Position = mul(V, transpose(WorldMatrix));
Output.Position = mul(Output.Position, transpose(ViewMatrix));
Output.Position = mul(Output.Position, transpose(ProjectionMatrix));
Output.UV = Input.UV;
Output.Colour = Input.Colour;
Output.Normal = Input.Normal;
return Output;
}
Here is my code for setting up the viewport (Width/Height are 1366/768 - the size of the window):
D3D11_VIEWPORT Viewport;
Viewport.Width = (float)Width;
Viewport.Height = (float)Height;
Viewport.MinDepth = 0.0f;
Viewport.MaxDepth = 1.0f;
Viewport.TopLeftX = 0.0f;
Viewport.TopLeftY = 0.0f;
DeviceContext->RSSetViewports(1, &Viewport);
| I've seen similar issues caused by:
Transposed matrices (are you using row major or column major matrices? Do you need a #pragma pack_matrix? It looks like you've finnicked with transposing quite a bit - avoid doing that, as you will make mistakes that are difficult to reason about)
Otherwise messed up matrix multiplication order. If you bob the camera up/down/left/right or arcball it around & rotate the model, does it actually work? Make sure you incorporate camera rotations with camera translations and object rotations / translations, otherwise you might incorrectly think your code works. What if you zoom near or far?
I recommend when debugging these issues that you first try running your shader transformations in CPU code:
Take a simple model-space coordinate (e.g. 0,0,0).
Pass it through your world matrix, and check if it looks right.
Pass it through your view matrix, verify it.
Then your proj matrix.
Even that simple test can be quite revealing. Basically, if you think your vertex shader is wrong, that's fortunately usually the easiest shader to validate in software! If this passes, try a few other vertices, like the vertices if your box. If that succeeds in software, then now you know it somehow has to do with how you're passing vertex data to the GPU (e.g. row-major vs column-major). If not, then you've built a simple CPU-side repro, great.
(Also, I'm not sure what your pixel shader is, but to rule it out and isolate the vertex shader, consider making the pixel shader just return a solid white)
|
71,998,383 | 72,070,391 | CLBlast library not working on Mingw-w64 with Nvidia GPUs | I am trying to run the example samples/sgemm.cpp from the CLBlast repo on
Windows 10 with a Nvidia graphics card. I have obtained the cl.hpp from the link. The makefile is simply as follows:
a.exe: sgemm.cpp
g++ sgemm.cpp -lopencl -clblast -O0 -g -DCL_TARGET_OPENCL_VERSION=300
I have the Nvidia CUDA toolkit v11.6 installed and the include directory is on the environment variable CPATH so that it is found by g++. Furthermore, the compiler is part of a Mingw-w64 installation on which clblast is installed.
The problem is that the compilation seems to succeed, but as soon as I try executing the a.exe it crashes without any error message. Similarly, attaching gdb does not help either, because the program exits immediatedly and gdb prints
During startup the program exited with code 0xc0000135.
What is the problem?
Update
I have opened an issue on the clblas github. Note that I can compile clinfo from here without problems. A missing library therefore should not be the first thing that comes to my mind.
| To answer this, this was not a problem with gdb, a.exe or the CUDA toolkit but rather with the installed library which is build with Visual Studio. The resulting binary seems to be incompatible with g++. Therefore, installing the library from source using g++ fixed this.
|
71,998,428 | 71,998,590 | how to write the result of sqlite3_exec not in stdout | I need to execute sql command "select" and return some data from the result of it. I'm trying to do it with sqlite3_exec, but it's only writting in stdout. What I need to do to write the data in array or something like this?
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
void my_exec(char * sql) {
sqlite3 *db;
char *zErrMsg = nullptr;
int rc;
//char * sql;
/* Open database */
rc = sqlite3_open("data_base.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
} else {
fprintf(stdout, "Opened database successfully\n");
}
/* Create SQL statement */
// sql
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, nullptr, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Success\n");
}
/* Close database */
sqlite3_close(db);
}
| Let's look at the fourth parameter of sqlite3_exec(). This is a pointer that is passed to the callback function. Give sqlite3_exec() a pointer to your data structure and store the results to that pointer in the callback.
You can for example use a vector:
std::vector<std::pair<std::string, std::string>> vec;
rc = sqlite3_exec(db, sql, callback, &vec, &zErrMsg);
The callback:
static int callback(void *dataPtr, int argc, char **argv, char **azColName){
auto vec = static_cast<std::vector<std::pair<std::string, std::string>>*>(dataPtr);
int i;
for(i=0; i<argc; i++){
vec->push_back({azColName[i], argv[i] ? argv[i] : "NULL"});
}
return 0;
}
|
71,998,434 | 71,998,911 | can not open include file cpr/cprver.h using CPR library in CPP application | Hello i work with CPR library in cpp application for http request to my api but after i add additional include directory, i am getting error like 'can not open include file cpr/cprver.h'
As i check there is no file with the name cprver.h in cpr folder.
What i did:
Download CPR library from https://github.com/whoshuu/cpr
Add library in cpp project using additional include directory : i give a path till D:\cpr-master\include.
#include <cpr/cpr.h>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
cpr::Response r = cpr::Get(
cpr::Url{ "https://jsonplaceholder.typicode.com/todos/1" });
cout << r.status_code << "\n"; // 200
cout << r.header["content-type"] << "\n"; // application/json;charset=utf-8
cout << r.text << "\n"; // JSON text string
return 0;
}
error: can not open include file cpr/cprver.h.
There is no error in code.
Hope i explain well. Thank you in advance.
| I think simply downloading cpr library from Github is not enough, you should build and link cpr against your binary.
According to the documentation, there are several ways to use cpr:
Cmake
If you already have a CMake project you need to integrate C++ Requests with, the primary way is to use fetch_content. Add the following to your CMakeLists.txt.
include(FetchContent)
FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git
GIT_TAG 6ea2dec23c3df14ac3b27b7d2d6bbff0cb7ba1b0) # The commit hash for 1.8.1. Replace with the latest from: https://github.com/libcpr/cpr/releases
FetchContent_MakeAvailable(cpr)
This will produce the target cpr::cpr which you can link against the typical way:
target_link_libraries(your_target_name PRIVATE cpr::cpr)
That should do it! There's no need to handle libcurl yourself. All dependencies are taken care of for you.
All of this can be found in an example here.
If you want to build your application on different platform, I think Cmake is the proper way to go.
vcpkg
Since you are working on Windows, I think vcpkg is the easy way to go:
You can download and install cpr using the vcpkg dependency manager:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install cpr
The cpr port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.
|
71,998,455 | 72,002,774 | Cast AlignedBox double to AlignedBox int | I'm trying to use Eigen AlignedBox. Specifically, I'm trying to cast a box of double into an int one, by using AlignedBox::cast
AlignedBox<double, 2> aabbox2d = AlignedBox<double, 2>(Vector2d(0.52342, 2.12315), Vector2d(3.87346, 4.72525));
aabbox2d.cast<AlignedBox<int, 2>>();
auto minx = aabbox2d.min().x();
Anyway, when the execution gets to min() I get an assert:
Assertion failed: (((SizeAtCompileTime == Dynamic && (MaxSizeAtCompileTime==Dynamic || size<=MaxSizeAtCompileTime)) || SizeAtCompileTime == size) && size>=0), function resize, file /Users/max/Developer/Stage/Workspace/AutoTools3D/dep/libigl/external/eigen/Eigen/src/Core/PlainObjectBase.h, line 312.
Note that this is different from casting a matrix scalar to another one. An object is implied.
Supposedly I'm not doing the cast correctly. Does someone know the right way?
Thank you
| Consulting the documentation for AlignedBox::cast shows that the template argument to cast is defined as template<typename NewScalarType> and the return value is *this with scalar type casted to NewScalarType. Thus the cast function does not modify the existing instance of the box, but returns a new one. To make your example work you need to store the returned instance like follows:
AlignedBox<double, 2> aabbox2d = AlignedBox<double, 2>(Vector2d(0.52342, 2.12315), Vector2d(3.87346, 4.72525));
AlignedBox<int, 2> casted = aabbox2d.cast<int>();
const int minx = casted.min().x();
You can play with this here: https://godbolt.org/z/ozE4rzebb
As a side note: as the documentation states, when working with Eigen one should refrain from using auto (probably not a problem in this case though)
|
71,998,722 | 71,999,005 | How can I get the faceIdlist from a vtkPolyhedron object in python? | I'm a learner of vtk, I want to use vtkpolyhedron object to describe an irregular polyhedron, then write it into .vtu file. It has an error when I write it into unstructured grid. I use a cube as example, here is my code
# create a cube polyhedron
polyhedron = vtkPolyhedron()
for i in range(8):
polyhedron.GetPointIds().InsertNextId(i)
polyhedron.Initialize()
polyhedron.GetPoints().InsertNextPoint(0, 0, 0)
polyhedron.GetPoints().InsertNextPoint(1, 0, 0)
polyhedron.GetPoints().InsertNextPoint(1, 1, 0)
polyhedron.GetPoints().InsertNextPoint(0, 1, 0)
polyhedron.GetPoints().InsertNextPoint(0, 0, 1)
polyhedron.GetPoints().InsertNextPoint(1, 0, 1)
polyhedron.GetPoints().InsertNextPoint(1, 1, 1)
polyhedron.GetPoints().InsertNextPoint(0, 1, 1)
face_1 = [6,
4, 0, 3, 2, 1,
4, 0, 4, 7, 3,
4, 4, 5, 6, 7,
4, 5, 1, 2, 6,
4, 0, 1, 5, 4,
4, 2, 3, 7, 6]
polyhedron.SetFaces(face_1)
# write into unstructured grid
polyGrid = vtkUnstructuredGrid()
polyGrid.InsertNextCell(polyhedron.GetCellType(), polyhedron.GetFaces())
The error is
Traceback (most recent call last):
File "D:/science/NMM/python-NMM/script/3D_script/vtk_study/011_convert_unstructured_grid_to_polydata.py", line 145, in <module>
polyGrid.InsertNextCell(polyhedron.GetCellType(), polyhedron.GetFaces())
TypeError: InsertNextCell argument %Id: %V
Then I try to print the polyhedron.getfaces
print(polyhedron.GetFaces())
print(type(polyhedron.GetFaces()))
I get
_0000013b5aca1e00_p_void
<class 'str'>
The document of vtkpolyhedron show it should return a vtkIdList https://vtk.org/doc/nightly/html/classvtkPolyhedron.html#a070ddbec07089276d5f4286b975c830d
Is there any error in the use process?
Thank you very much!
| You should call Initialize after SetFaces (at least before further access to the cell)
See this similar example
In found from this doc
Edit
As GetFaces does not seem to work as expected in python I advise to create your data following the pattern of this other example:
create a vtkPoints, add it to the vtkUnstructuredGrid
create a vtkIdList to list the point ids for each face
Add the polyhedron cell to the grid: ugrid.InsertNextCell(VTK_POLYHEDRON, cellIdList)
|
71,998,729 | 72,039,433 | Save a captured image using QCameraImageCapture::capture() in PNG Format | this is literally my first question in a forum.
So I'm a Qt newbie and I'm stuck at this little detail.
I'm creating this application that takes pictures and saves them, but the issue is that it saves then in a "JPEG" format and i need them in "PNG" or "GIF" or "tiff" and i I've tried a lot of stuff but nothing worked, so here's my code :
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
_camera_view = new QCameraViewfinder();
_take_image_button = new QPushButton("Take Image");
_turn_camera_off = new QPushButton("Turn Off");
_turn_camera_on= new QPushButton("Turn On");
_central_widget = new QWidget();
setCentralWidget(_central_widget);
_setup_ui();
_setup_camera_devices();
set_camera(QCameraInfo::defaultCamera());
connect(_take_image_button, &QPushButton::clicked, [this]{
_image_capture.data()->capture();});
connect(_turn_camera_off, &QPushButton::clicked, [this]{_camera.data()->stop();});
connect(_turn_camera_on, &QPushButton::clicked, [this]{_camera.data()->start();});}
| For anyone that might encounter this problem in the future, here's the solution i've found :
_image_capture->setCaptureDestination(QCameraImageCapture::CaptureToBuffer);
QObject::connect(_image_capture.data(), &QCameraImageCapture::imageCaptured, [=] (int id, QImage img) {
fileName = "image.png";
path = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation) + "/" + fileName;
img.save(path, "PNG");
});
|
71,998,853 | 72,076,306 | create shared library with main to call undefined function and provide function body in other project | I need to create a shared library using cmake, and I must call function run() in a library function. But the project which uses this library should provide the body of this function.
The real cases use systemC which force library to implement main function. To avoid further complexity, I try to simplify the case like this:
MyInterface.h
void run();
MyLibraryAction.cpp
#include "MyInterface.h"
int main(){
run();
}
The cmake content is:
add_library(mylib SHARED MyLibraryAction.cpp)
set_target_properties(mylib PROPERTIES PUBLIC_HEADER MyInterface.h)
configure_file(mylib.pc.in mylib.pc @ONLY)
install(
TARGETS mylib
DESTINATION ${CMAKE_INSTALL_LIBDIR}
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES ${CMAKE_BINARY_DIR}/mylib.pc
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig)
I am wondering if that is possible. If so, am I doing it right? is using extern relevant in this context?
I am get error when I try to build and create the library:
undefined reference to run()
| As mentioned in the comments, weak symbols worked fine in this case.
MyInterface.h
void run();
and then have an implementation for run function with weak symbol:
InterfaceWeakImplementation.h
void __attribute__((weak)) run(){
// pass
}
and have the actual implementation in caller project
InterfaceStrongImplementation.h
void run(){
// Some real work
}
|
71,998,977 | 71,999,084 | std::chrono and missing (?) support for negative leap seconds | C++20 added time zone support to std::chrono, and this includes leap seconds. However, it appears as if only leap second insertion was supported, not leap second removal, that is, negative leap seconds. (Admittedly, since 1972 there only have been positive leap seconds; but it seems that in the last few years the drift has reversed, and a negative leap second seems possible in the upcoming years.)
This is evident from the way the std::chrono::leap_second class is described - there's no way to tell positive from negative leap seconds.
Is it known why std::chrono doesn't support this possibility? Was this an optimization, or a mistake of some sort? Or is it supported already and I have missed something?
Note: The MSVC implementation seems to have a nonstandard feature that allows negative leap seconds.
| [time.zone.leap.members]/2 actually does specify negative leap seconds.
Returns: +1s to indicate a positive leap second or -1s to indicate a negative leap second.
[Note 1: All leap seconds inserted up through 2019 were positive leap seconds. — end note]
When the standard speaks of insertion of a leap second, that leap second could be negative, which would be the same as a removal.
Note: I am unsure if this is new to C++23 or also in C++20, I don't have a copy of the C++20 draft with me right now.
|
71,999,513 | 71,999,540 | use the 'typename' keyword to treat nontype "pcl::PointCloud<PointT>::Ptr [with PointT=T]" as a type in a dependent contextC/C++(2675) | I wrote two functions.
PointCloud<PointXYZ>::Ptr rotateCloud(PointCloud<PointXYZ>::Ptr src);
PointCloud<PointXYZRGB>::Ptr rotateCloud(PointCloud<PointXYZRGB>::Ptr src);
In these two functions, I write completely same code without inside <>. <PointXYZ> or <PointXYZRGB>.
I want to write a single function.I heard there is Template.I tried it.
template <typename T>
PointCloud<T>::Ptr rotateCloud(PointCloud<T>::Ptr src);
I got error.
use the 'typename' keyword to treat nontype "pcl::PointCloud<PointT>::Ptr [with PointT=T]" as a type in a dependent contextC/C++(2675)
I can't understand this error message.
Anyone can understand?
| Since ::Ptr is a dependent type you need typename on the argument and return type
template <typename T>
typename PointCloud<T>::Ptr rotateCloud(typename PointCloud<T>::Ptr src);
|
72,000,110 | 72,001,677 | How to automatically make a calculation in a cell in the same row using the data of another cell that is changed in QtableWidget? | Basically I have a table widget. 2 columns in that table contain Diameters and Area repsectively.
I basically want when I enter the diameter the area get calculated in the corresponding cell. And if I enter the area, the diameter is similarly calculated.
I made the connect function that sends a signal when a cell is changed, this is used to detect the row and column to know which cell exactly and the SLOT is the function where the calculations happen. So this:
QObject::connect(TabUI.tableWidget, &QTableWidget::itemChanged, this, &Pressurator::CalculateArea);
And this:
void Pressurator::CalculateArea(QTableWidgetItem *item)
{
// QTableWidgetItem * item = new QTableWidgetItem;
// double area = 0;
// QDoubleSpinBox * diameter_SB = static_cast<QDoubleSpinBox*>(TabUI.tableWidget->cellWidget(item->row(),0));
// QDoubleSpinBox * area_SB = static_cast<QDoubleSpinBox*>(TabUI.tableWidget->cellWidget(item->row(),1));
// area = M_PI * qPow(diameter_SB->value()/2, 2);
// area_SB->setValue(area);
row = item->row();
column = item->column();
qDebug()<<"DETECTED--->"<<row<<" | "<<column;
if(column == 0){
diameter = TabUI.tableWidget->item(row,0)->text().toDouble();
qDebug()<<"Diameter: "<<diameter<<Qt::endl;
area = M_PI * qPow(diameter/2, 2);
qDebug()<<"Area: "<<area<<Qt::endl;
TabUI.tableWidget->item(row,1)->setText(QString::number(area, 'f', 6));
}else if(column == 1){
area = TabUI.tableWidget->item(row,1)->text().toDouble();
diameter = qSqrt((4* area)/M_PI);
TabUI.tableWidget->item(row,0)->setText(QString::number(diameter, 'f', 6));
}
My app keeps crashing after I enter data in one of the cells, so I don't really know how to proceed or the reason for the crash.
| I just defined my tableWidget when constructing my form (not at the CalculateArea function) as below and it worked:
QTableWidget* tableWidget = new QTableWidget();
tableWidget->setRowCount(1);
tableWidget->setColumnCount(2);
QTableWidgetItem* item = new QTableWidgetItem("1.0");
QTableWidgetItem* item2 = new QTableWidgetItem("0.785398");
tableWidget->setItem(0, 0, item);
tableWidget->setItem(0, 1, item2);
tableWidget->show();
In QTableWidget class, the signal "itemChanged" is emitted whenever the data of item has changed. In the definition of "CalculateArea" slot, you are trying set the data which causes to emit another signal. So it will be stuck in stack overflow. You can block the signal before you are trying set the data.
row = item->row();
column = item->column();
TabUI.tableWidget->blockSignals(true);
.
. // Set your data (if / else if) ...
.
TabUI.tableWidget->blockSignals(false);
|
72,000,286 | 72,000,457 | custom type_index order without boost | I have the following map :
std::map<std::type_index, std::set<Status *>> statuses;
It store sets of the different subclasses of Status there, thanks to their std::type_index.
However I want to have control about the order of the objects in this map (for instance, I have two classes Burn and Stun that inherit from Status, and I would like typeid(Stun) < typeif(Burn) so that when I iterate through the map I get the std::set<Stun> before the std::set<Burn>).
I thought about implementing a custom type_index class but I can't seem to find any way to do this without boost, which is a huge library that I would like not to have to include to my project.
Any advice on how to have a custom order in the map?
| You can wrap the type_index into a custom type with a comparator that yields the desired order.
The example from cppreference modified using std::map rather than std::unordered_map and with a custom comparator:
#include <iostream>
#include <typeinfo>
#include <typeindex>
#include <map>
#include <string>
#include <memory>
struct A {
virtual ~A() {}
};
struct B : A {};
struct C : A {};
struct my_type_index {
std::type_index index = std::type_index(typeid(void));
my_type_index() = default;
my_type_index(std::type_index i) : index(i) {}
bool operator<(const my_type_index& other) const {
static std::map< std::type_index,int> rank{
{ std::type_index(typeid(A)) , 1},
{ std::type_index(typeid(B)), 2},
{ std::type_index(typeid(double)), 3},
{ std::type_index(typeid(int)), 4},
{ std::type_index(typeid(C)), 5}
};
return rank[index] < rank[other.index];
}
};
int main()
{
std::map<my_type_index, std::string> type_names;
type_names[std::type_index(typeid(int))] = "int";
type_names[std::type_index(typeid(double))] = "double";
type_names[std::type_index(typeid(A))] = "A";
type_names[std::type_index(typeid(B))] = "B";
type_names[std::type_index(typeid(C))] = "C";
for (const auto& e : type_names) {
std::cout << e.first.index.name() << " " << e.second << "\n";
}
}
output:
1A A
1B B
d double
i int
1C C
With improvements suggested by François Andrieux:
struct my_type_index {
std::type_index index = std::type_index(typeid(void));
int rank = 0;
my_type_index() = default;
my_type_index(std::type_index i) : index(i) {
auto it = ranks.find(i);
if (it != ranks.end()) rank = it->second;
}
static const std::map<std::type_index,int> ranks;
bool operator<(const my_type_index& other) const {
return rank < other.rank;
}
};
const std::map<std::type_index,int> my_type_index::ranks = [](){
std::map<std::type_index,int> result;
std::type_index index_order[] = {
std::type_index(typeid(A)),
std::type_index(typeid(B)),
std::type_index(typeid(double)),
std::type_index(typeid(int)),
std::type_index(typeid(C))
};
for (size_t i = 0; i < std::size(index_order);++i){ result[ index_order[i]] = i+1; }
return result;
}();
The ranking is stored in the static map ranks and each instances rank is already evaluated on construction (instead of on each comparison, ie comparisons are now cheaper). Also the map is now generated from an array, which is more robust (you cannot mistype the index/rank anymore). Further, the map is const, ie find instead of operator[] is used for look up. Elements not in the map will be assigned rank 0. Actually that was also the case before, but before operator[] was potentially adding unnecessary elements to the map.
|
72,000,618 | 72,003,582 | Not receiving an Appropriate Result, USACO Bronze 2015 Fence Problem | I was attempting the Fencing Problem of USACO 2015 Bronze.
http://www.usaco.org/index.php?page=viewproblem2&cpid=567
This problem basically asks you to find the total length of the fence painted given that two individuals (a cow and farmer) paint fences between a given interval on the number line (the fence is the number line over here). The painting can overlap, we need to find the total length of fence finally covered in paint.
This is my code but I don't get the required result even though I am not able to find a logical error with in my solution, probably there is some error in the syntax of my code.
CODE:
#include <iostream>
#include <string>
using namespace std;
int main() {
int lowerlimit, upperlimit, a, b, c, d, length;
cin >> a >> b >> c >> d;
if (a < c) {
lowerlimit = a;
}else{
lowerlimit = c;
}
if (b > d) {
upperlimit = b;
}else{
upperlimit = d;
length = upperlimit - lowerlimit;
}
cout << length;
return 0;
}
INPUT:
7 10
4 8
OUTPUT:
I get extremely large different numbers each time (For example: 1063908272)
I am also open to any suggestions to improve my code if it is redundant, I am a beginner.
| 1. length might not be initialized
Like @AlanBirtles pointed out in the comments, length would not be initialized in case b <= d which would lead to undefined behaviour.
This could be fixed by moving the assignment of length outside the else statement:
godbolt example
#include <iostream>
#include <string>
using namespace std;
int main() {
int lowerlimit, upperlimit, a, b, c, d, length;
cin >> a >> b >> c >> d;
if (a < c) {
lowerlimit = a;
}else{
lowerlimit = c;
}
if (b > d) {
upperlimit = b;
}else{
upperlimit = d;
}
length = upperlimit - lowerlimit;
cout << length;
return 0;
}
After this your program will already produce the expected outcome (assuming you get the input via stdin and need to output to stdout)
2. Do you need to read the input file / write to the output file?
In the problem statement link you posted there's an explicit mention of an input file (paint.in) and output file (paint.out) - so it might be that you're expected to read your input from that file instead of from stdout (like @Qingchuan Zhang mentioned in his answer)
In case you don't get any stdin input, your a, b, c & d would be left uninitialized und you'd get undefined behaviour once you try to use them.
So in case you're actually required to read the input from a file, you'd have to change your code for that, e.g.:
int main() {
int lowerlimit, upperlimit, a, b, c, d, length;
std::ifstream input("paint.in");
input >> a >> b >> c >> d;
if (a < c) {
lowerlimit = a;
}else{
lowerlimit = c;
}
if (b > d) {
upperlimit = b;
}else{
upperlimit = d;
}
length = upperlimit - lowerlimit;
std::ofstream output("paint.out");
output << length;
return 0;
}
3. Potential improvements to your code
This is just a small list of things that i'd personally change, YMMV.
The if statements for lowerlimit / upperlimit effectively do what std::min / std::max would do, respectively. So i'd go with the standard version, e.g.:
int a, b, c, d;
cin >> a >> b >> c >> d;
cout << max(b, d) - min(a, c);
using namespace std; - Including the entire std namespace might be convenient, but it's rather easy to create ambiguity problems with it - which is why it's recommended to never include namespaces as a whole (see isocpp coding standards / Why is "using namespace std;" considered bad practice? )
Although it doesn't matter that much for a short piece of code, it's a good habit to get into typing std:: out every time.
So we end up with this:
#include <iostream>
#include <string>
int main() {
int a, b, c, d;
std::cin >> a >> b >> c >> d;
std::cout << std::max(b, d) - std::min(a, c);
return 0;
}
Variable names: I do agree with @digito_evo's comment that in general more descriptive variable names would be nice - but in the question you've linked they're also called a, b, c, d - so in this case i'd probably leave them as they are to make them consistent with the question.
Error checking. Whenever you do something that might fail (reading from stdin, writing to file, etc...) it's generally a good idea to check if what you tried was actually successful (in this case a, b, c, d might be left uninitialized in case the input operation fails)
In this case you can just check if std::ios_base::iostate::failbit is set on the stream, which would indicate that one of the int's failed to be properly parsed. (in this case i'm using std::ios::operator bool() to test it):
int a, b, c, d;
std::cin >> a >> b >> c >> d;
if(!std::cin) {
std::cout << "Invalid input!";
return 1;
}
std::cout << std::max(b, d) - std::min(a, c);
return 0;
So after incorporating all those things this is what i ended up with:
godbolt example
#include <iostream>
#include <string>
int main() {
int a, b, c, d;
std::cin >> a >> b >> c >> d;
if(!std::cin) {
std::cout << "Invalid input!";
return 1;
}
std::cout << std::max(b, d) - std::min(a, c);
return 0;
}
|
72,000,637 | 72,000,871 | How can I connect a QML signal to a C++ slot within the QML file | according to this, I can connect qml signal and c++ slot in qml file without QObject::connect in c++ file.
But all I got is an error Expected token ':' in
Window {
signal sizeChange(int y, int width, int height)
visible: true
width: 1920
height: 1080
sizeChange.connect(cefWindow.resizeCEFWindow)
^
| Expected token ':'
}
| There's a couple different ways you could do it. You could put your code in a function as @Amfasis mentioned:
Window {
Component.onCompleted: {
sizeChange.connect(cefWindow.resizeCEFWindow)
}
}
Or you could just directly call your C++ slot from a signal handler, like this:
onSizeChange: {
cefWindow.resizeCEFWindow()
}
I usually prefer the second method myself.
|
72,000,848 | 72,001,352 | How to safely get the new filename from SHNotify event (SHCNE_RENAMEITEM) | I've hooked into the Windows shell, and am receiving notification events nicely to my hidden CWnd.
When I receive the SHCNE_RENAMEITEM event, the SHGetPathFromIDList() function returns me the old file name, but not the new file name of the rename.
I've successfully hacked a pointer and discovered the new name, but this does not feel very safe to me. I tried using ILNext/ILGetNext/ILIsEmpty to iterate the list, but these do not give me the new name. Is there a safer way?
afx_msg LRESULT OnChange(WPARAM wParam, LPARAM lParam)
{
long lEvent = 0L;
PIDLIST_ABSOLUTE* rgpidl=nullptr;
TCHAR szFileOld[MAX_PATH] = L"\0";
TCHAR szFileNew[MAX_PATH] = L"\0";
HANDLE hNotifyLock = SHChangeNotification_Lock((HANDLE)wParam, (DWORD)lParam, &rgpidl, &lEvent);
if (!SHGetPathFromIDListW((struct _ITEMIDLIST*)*rgpidl, szFileOld))
return TRUE;
if (lEvent & SHCNE_RENAMEITEM)
{
struct _ITEMIDLIST* pNext = (struct _ITEMIDLIST*)*(&rgpidl[1]); // yes, I got lucky guessing the synatx.
if (ILIsEmpty(pNext)) // probably not much safety on this, but trying to be kind.
return TRUE;
if (!SHGetPathFromIDListW(pNext, szFileNew))
return TRUE;
}
// other code.
return FALSE;
}
I should mention my registration code is using the New Delivery method.
BOOL fRecursive = FALSE;
UINT uMsg = WM_FILE_CHANGED;
long lEvents = SHCNE_UPDATEITEM | SHCNE_DELETE | SHCNE_CREATE | SHCNE_RENAMEITEM | SHCNE_UPDATEDIR;
int const nSources = SHCNRF_ShellLevel | SHCNRF_InterruptLevel | SHCNRF_NewDelivery;
SHChangeNotifyEntry const entries[] = { pidlWatch, fRecursive };
m_lNotificationRegistry = SHChangeNotifyRegister(m_pWnd->m_hWnd, nSources, lEvents, uMsg, ARRAYSIZE(entries), entries);
| You are on the right track, but your syntax is just over-complicated. SHChangeNotification_Lock() will give you a pointer to an array of PIDLs, you don't need fancy type-casts to access the elements of that array.
Also, you need to call SHChangeNotification_Unlock() before exiting your callback function.
Try something more like this instead:
afx_msg LRESULT OnChange(WPARAM wParam, LPARAM lParam)
{
long lEvent = 0L;
PIDLIST_ABSOLUTE* rgpidl = nullptr;
HANDLE hNotifyLock = SHChangeNotification_Lock((HANDLE)wParam, (DWORD)lParam, &rgpidl, &lEvent);
if (lEvent & SHCNE_RENAMEITEM)
{
WCHAR szFileOld[MAX_PATH] = L"\0";
WCHAR szFileNew[MAX_PATH] = L"\0";
SHGetPathFromIDListW(rgpidl[0], szFileOld);
SHGetPathFromIDListW(rgpidl[1], szFileNew);
}
// other code.
SHChangeNotification_Unlock(hNotifyLock);
return FALSE;
}
|
72,001,238 | 72,001,796 | binding multiple texture in OpenGL does not work correctly | I am tired of binding multiple textures
I have something weird when I have 2 textures or more, it's over each other
This problem happens when using GPU: NVIDIA GeForce RTX 3070 Laptop GPU/PCIe/SSE2
and openGL Version 4.6 like this:
but when using GPU: AMD Radeon(TM) Graphics it pretty good Like this
main.cpp
shaderProgram.bind();
const int NUMBER_OF_TEXTURE = textures.size();
auto sample = new int[NUMBER_OF_TEXTURE];
for (int i = 0; i < NUMBER_OF_TEXTURE; i++)
sample[i] = i;
shaderProgram.setUniform1iv("u_Textuers", NUMBER_OF_TEXTURE, sample);
delete[] sample;
while (!glfwWindowShouldClose(window))
{
processInput(window);
Renderer::clear();
shaderProgram.bind();
for (int i = 0; i < NUMBER_OF_TEXTURE; i++)
{
textures[i].Bind(i);
}
render.draw(shaderProgram);
GLCall(glBindTexture(GL_TEXTURE_2D, 0))
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window);
glfwPollEvents();
}
Texture.cpp
Texture::Texture(const FxrDataStructures::Image& image)
:m_RendererID(0), m_LocalBuffer(nullptr),
m_Width(0), m_Height(0), m_BPP(0)
{
GLCall(glCreateTextures(GL_TEXTURE_2D, 1, &m_RendererID));
GLCall(glBindTexture(GL_TEXTURE_2D, m_RendererID));
// set the texture wrapping/filtering options (on the currently bound texture object)
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR))
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR))
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE))
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE))
m_Width = image.getWidth();
m_Height = image.getHeight();
m_BPP = image.getBitDepth();
cv::Mat mat = image.img;
cv::flip(mat, mat, 0);
m_LocalBuffer = mat.ptr();
if (m_LocalBuffer)
{
GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_LocalBuffer))
//GLCall(glGenerateMipmap(GL_TEXTURE_2D))
}
else
{
LOG_DEBUG("Failed to load texture ");
}
GLCall(glBindTexture(GL_TEXTURE_2D, 0))
}
void Texture::Bind(unsigned int slot) const
{
GLCall(glBindTextureUnit(slot, m_RendererID))
}
fragment shader
in float IndexMaterial;
uniform sampler2D u_Textuers[32];
void main()
{
float diff;
const int index = int(IndexMaterial);
FragColor = vec4(texture(u_Textuers[index], TexCoord));
}
| I'd say this has something to do with the int-to-float conversion. It seems that the NVIDIA GPU adds a little bit of random noise when it interpolates IndexMaterial, while the AMD GPU does not.
Try using flat shading for IndexMaterial. This will cause the GPU to use the value from one vertex, instead of interpolating between vertices:
flat in float IndexMaterial;
See: "flat" qualifier in glsl?
You may also change IndexMaterial from float to int, since it has no good reason to be float.
|
72,001,662 | 72,001,823 | C++ declare zoned_time for 1 PM today east coast time | I'm looking for how to declare a time for a configurable number of minutes before 1 pm east coast time on the day of running the program. I've found ways to get a fixed time of the timezone such as:
chrono::zoned_time onePmEastCoastTime ("New York/New York", chrono::sys_days{ 2022y / chrono::April/ 15d } + 13h );
How can I declare a configurable time that will match a specific timezone?
| It sounds like you want to specify the time in terms of local time as opposed to UTC. The key to this is in the use of local_days vs sys_days.
sys_days is a count of days in UTC.
local_days is a count of days in some local time that can be subsequently paired with a timezone.
Maybe you are looking for:
chrono::minutes m = ...
chrono::zoned_time onePmEastCoastTime{"America/New_York",
chrono::local_days{ 2022y / chrono::April/ 15d } + 13h - m};
|
72,002,028 | 72,002,106 | How is it that we're allowed to create a const std::vector without any initializer unlike normal const objects | I am learning about std::vector in C++. I learnt that a const std::vector<int> means that we cannot change the individual elements within that vector and also cannot append/push_back more elements into it i.e., we only have read-access to the elements, which is expected from an entity that is a const. But i find a difference when defining a const std::vector than defining other const types like int, double etc. The situation is shown below:
int main()
{
const int i; //doesn't compiler as expected: initializer needed here
const std::vector<int> vec1 ; //COMPILES FINE: WHY ISN'T AN INITIALIZER NEEDED HERE?
}
As we can see that for a const built in type(like int), we must provide an initializer.
My first question is that why isn't this the case for std::vector. That is, how(why) are we allowed to omit the initializer for a const vector. I mean the const vector means that we won't be able to add elements into it so it seems that this vec1 is useless(practically) now.
So my second question is that is there a use for vec1 ? I mean since the standard allows this so they may have already thought about this case and found out that this vec1 can be useful somewhere. That is, what are the use cases for this vec1 that had no initializer at the time of its definition.
|
As we can see that for a const built in type(like int), we must provide an initializer.
That is incorrect. You must ensure that a const object is initialized.
If you do not provide an initializer for an object, that object will undergo the process of default initialization:
To default-initialize an object of type T means:
If T is a (possibly cv-qualified) class type ([class]), constructors are considered. The applicable constructors are enumerated ([over.match.ctor]), and the best one for the initializer () is chosen through overload resolution ([over.match]). The constructor thus selected is called, with an empty argument list, to initialize the object.
If T is an array type, each element is default-initialized.
Otherwise, no initialization is performed.
vector<int> is a class type, so the first option is used. The default constructor will be called to initialize it.
int is not a class type. It is also not an array type. Therefore, no initialization is performed. And if this happens to a const object, the code is ill-formed.
For initializing const object, further rules exist:
If a program calls for the default-initialization of an object of a const-qualified type T, T shall be a const-default-constructible class type or array thereof.
int is not a class type or array of class types at all. So any attempt to create a const-qualified object of type int with default-initialization violates this rule and is ill-formed.
vector<int> happens to follow the rules of const-default-constructible, which is why your code works.
As to whether this particular object is "useful", that's up to you. It's an empty vector<int> which cannot be made non-empty. If that's useful to you in some circumstance, then it is useful.
|
72,002,196 | 72,002,738 | Get Disjunctive Support for itemset? | Disjunctive Support :
let an itemset I formed by any non-empty subset from C
Supp(I) is the number of transactions containing at least one item of I for example i have :
vector < vector <int> > transactions = {{1, 2},
{2, 3, 7},
{4,6},
{1,5,8}};
vector<int> I ={1,2};
expected result :
Supp(I) = 3
but my code return Supp(I) = 1
#include <iostream>
#include <vector>
using namespace std;
int getSupport(vector < vector<int> > &transactions, vector<int> item) {
int ret = 0;
for(auto&row:transactions){
int i, j;
if(row.size() < item.size()) continue;
for(i=0, j=0; i < row.size();i++) {
if(j==item.size()) break;
if(row[i] == item[j]) j++;
}
if(j==item.size()){
ret++;
}
}
return ret;
}
int main() {
vector < vector <int> > transactions = {{1, 2},
{2, 3, 7},
{4,6},
{1,5,8}};
vector <int> I={1,2};
int D = getSupport(transactions, I);
printf("Disjunctive support = %d",D);
return 0;
}
| You wrote that:
Supp(I) is the number of transactions containing at least one item of
I
But your implementation looks like you are trying to count transactions containing all the items of I.
Anyway if you still need implementation for the defintion you supplied, you can try this:
#include <iostream>
#include <vector>
int getSupport(std::vector<std::vector<int>> const & transactions, std::vector<int> const & item) {
int ret = 0;
for (auto const & tran : transactions) {
bool bFoundAtLeastOne{ false };
for (auto const & tran_elem : tran) {
for (auto const & item_elem : item)
{
if (tran_elem == item_elem)
{
ret++;
bFoundAtLeastOne = true;
break;
}
}
if (bFoundAtLeastOne) {
break;
}
}
}
return ret;
}
int main() {
std::vector<std::vector<int>> transactions =
{ { 1, 2 },
{ 2, 3, 7 },
{ 4,6 },
{ 1,5,8 } };
std::vector<int> I = { 1,2 };
int D = getSupport(transactions, I);
printf("Disjunctive support = %d\n", D);
return 0;
}
Some notes:
Better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?
I changed passing all the vectors by const& for efficiency and safety.
|
72,002,459 | 72,002,864 | Mixing cl, clang-cl and clang in the same project | Context
I am developing a cross-platform project that depends on a highly performance sensitive open-source library. This library supports a number of different compilers, but the most performant version is compiled via clang, due to inline assembly which isn't supported by the MSVC compiler (cl). This has highlighted to me that clang is capable of compiling code on Windows, and emitting highly performant dll libraries, but that there is also a deficit in my understanding of the interoperability of the MSVC toolchain and the clang ecosystem.
Question
To what extent is code compiled with clang, interoperable with the MSVC toolchain?
Are binaries emitted by clang ABI compatible with binaries emitted by cl, up to and including the latest language standard?
Specifically, can a static library (.a) compiled with clang be consumed by the MSVC toolchain? (ie. symbol definitions are not dllexport/imported).
Can clang emit 32-bit binaries?
I recognise clang-cl is simply a driver for clang, but are there any practical limitations or other reasons not to favour clang-cl over cl for new projects?
|
Specifically, can a static library (.a) compiled with clang be consumed by the MSVC toolchain? (ie. symbol definitions are not
dllexport/imported).
Yes. I have a fairly large Windows (MFC-based) project in which I use the native MSVC compiler to build all components that actually use any MFC (or other WinAPI) code, but use clang-cl for one particular "core" module (built as a static library). All code in that core module is strictly Standard-compliant (C++17, currently, but vide infra). I have been using this MSVC+clang combination for some years and have yet to experience any issues related to ABI incompatibility. (But note that static libraries on Windows have the ".lib" extension, not ".a".)
Are binaries emitted by clang ABI compatible with binaries emitted by cl, up to and including the latest language standard?
Yes – but you'll need VS 2022 for C++20 or later: The clang-cl compiler (V11) that comes with VS 2019 only recognizes up to (and including) C++17; however, clang-cl V13 (as installed by VS 2022) can be set to use C++20 or C++23. (Also note that the library I mentioned above makes heavy use of the "STL" containers, like std::vector.)
Can clang emit 32-bit binaries?
Yes. Switching between 64-bit and 32-bit target architectures within the VS IDE works equally well for both MSVC and clang-cl projects. This also seems to work when switching to ARM64 targets (assuming you have installed the required tools), but I can't verify the final output, as I don't have access to an ARM64-based Windows system.
I recognise clang-cl is simply a driver for clang, but are there any practical limitations or other reasons not to favour clang-cl over cl
for new projects?
I have tried building my entire project with the clang-cl tools but – so far – without success. This may be due to the fact that I am using MFC (I get a whole chunk of duplicate and/or missing symbols at link time). However, building simple, console-mode programs for Windows with clang-cl works just fine.
And, one further note: The run-time performance of my final program is considerably greater (i.e. faster) when compiling that core library with clang-cl, compared to the same code compiled with MSVC.
|
72,002,717 | 72,002,817 | Using std::thread outside main source file in c++ | I'm trying to use thread but it doesn't work outside main source file.
For example it doesn't work
void Game::foo() {
std::cout << "Why are you not working properly";
}
void Game::threadStart() {
std::thread th(foo); //here is something wrong
}
But this works(it is in main source file)
void foo() {
std::cout << "I'm working properly";
}
void thread() {
std::thread th(foo);
}
What more, when in 2nd option in main file when i want to use pointer on function it doesn't work.
Resource* res = new Resource();
Pocket* pock = new Pocket();
void thread() {
std::thread th(res->product,pock); // pock is an arg of function product();
}
Any suggestion how to fix it. In the second code I could send pointers as parms and then use
res->product(pock)
but I think using to functions two use 1 thread witch use another function is stupid.
| In your Game class example, you are trying to use a class member function as the thread function. This will work, but member functions have the hidden 'this' argument.
So you need something like:
void Game::threadStart() {
std::thread th(&Game::foo, this);
}
|
72,002,992 | 72,025,161 | How to link spacy-cpp lib with CMake | I'm working on a project atm where I want to use the lib spacy-cpp.
It's a header-only wrapper for the lib spaCy which is a Python lib.
Now the problem is that I'm not able to properly link the lib when using CMake but it works if I use a makefile. Here's an example how a working makefile looks like:
CXX = g++ -g -std=c++0x
MAIN = $(basename $(wildcard *Main.cpp))
OBJECTS = $(addsuffix .o, $(filter-out %Main %Test, $(basename $(wildcard *.cpp))))
HEADERS = $(wildcard *.h)
LIBS = -lspacy -I/usr/include/python3.8
.PRECIOUS: %.o
all: compile
compile: $(MAIN)
%Main: %Main.o $(OBJECTS)
$(CXX) -o $@ $^ $(LIBS)
%.o: %.cpp $(HEADERS)
$(CXX) -c $< $(LIBS)
clean:
rm -f *.o
rm -f $(MAIN)
The important part is LIBS.
Here's how I tried to add it in my CMake:
cmake_minimum_required(VERSION 3.21)
project(untitled)
set(CMAKE_CXX_STANDARD 14)
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
add_executable(untitled main.cpp)
target_link_libraries(untitled ${PYTHON_LIBRARIES})
This leads to the error:
====================[ Build | untitled | Debug ]================================
/home/me/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/213.7172.20/bin/cmake/linux/bin/cmake --build /home/me/desktop/dir/untitled/cmake-build-debug --target untitled
[1/2] Building CXX object CMakeFiles/untitled.dir/main.cpp.o
FAILED: CMakeFiles/untitled.dir/main.cpp.o
/usr/bin/c++ -I/usr/include/python3.8 -g -std=gnu++14 -MD -MT CMakeFiles/untitled.dir/main.cpp.o -MF CMakeFiles/untitled.dir/main.cpp.o.d -o CMakeFiles/untitled.dir/main.cpp.o -c /home/me/desktop/dir/untitled/main.cpp
In file included from /usr/local/include/spacy/attrs.h:12,
from /usr/local/include/spacy/spacy:12,
from /home/me/desktop/dir/untitled/main.cpp:2:
/usr/local/include/spacy/pyobjectptr.h:32:10: fatal error: pyobjectptr.cpp: File or directory not found
32 | #include "pyobjectptr.cpp"
| ^~~~~~~~~~~~~~~~~
compilation terminated.
ninja: build stopped: subcommand failed.
How can I translate this into my CMake file?
I read all the related posts on here but nothing seems to work. I appreciate all the help I could get from you.
| We now found the solution to my problem, maybe in the future someone else
has the same problem so I wanted to post it here.
This worked for me:
project(untitled)
set(CMAKE_CXX_STANDARD 14)
find_library(SPACY_LIB spacy)
include_directories(/usr/include/python3.8)
add_executable(untitled main.cpp)
target_link_libraries(untitled PUBLIC "${SPACY_LIB}")
Thanks for all the help.
|
72,003,202 | 72,007,952 | Can not connect a Surface eglCreatePbufferFromClientBuffer | VGint num_config;
EGLint value;
EGLBoolean ret;
m_BackLayerBuffer = vgCreateImage(SGA_DIS_FMT_RGB565, LCD_WIDTH, LCD_HEIGHT, VG_IMAGE_QUALITY_NONANTIALIASED);
vgClearImage(m_BackLayerBuffer, 0, 0, LCD_WIDTH, LCD_HEIGHT);
m_Context = eglGetCurrentContext();
m_Display = eglGetCurrentDisplay();
eglGetConfigs(m_Display, NULL, NULL, &num_config);
m_DrawSurface = eglGetCurrentSurface(EGL_DRAW);
ret = eglChooseConfig(m_Display, attribute_list, &m_Config, 1, &num_config);
m_OffScreenContext = eglCreateContext(m_Display, m_Config, EGL_NO_CONTEXT, NULL);
m_ImageSurface = eglCreatePbufferFromClientBuffer(m_Display, EGL_OPENVG_IMAGE, (EGLClientBuffer)m_BackLayerBuffer, m_Config, NULL);
value = eglGetError();
ret = eglMakeCurrent(m_Display, m_ImageSurface, m_ImageSurface, m_OffScreenContext);
m_ImageSurface always 0, and the error is EGL_BAD_ACCESS. the config is error?
| I know that, this hardware can not supoort muti context. After I delete
m_OffScreenContext = eglCreateContext(m_Display, m_Config, EGL_NO_CONTEXT, NULL);
the return value is EGL_SUCCESS
|
72,003,284 | 72,003,442 | GL_CULL_FACE hides one triangle from the front | I have run into a problem using C++ and OpenGL (GLFW and GLAD). When I use GL_CULL_FACE, it only hides one triangle and it hides it from the front of my cubes. If I use GL_FRONT or GL_BACK, the same thing happens but it only shows the opposite triangles.
These are my vertices and indices that I'm currently using:
static GLfloat vertices[] = {
// front face
0.5, 0.5, -0.5, // 0
-0.5, 0.5, -0.5, // 1
-0.5, -0.5, -0.5, // 2
0.5, -0.5, -0.5, // 3
// right face
0.5, 0.5, -0.5, // 4
0.5, 0.5, 0.5, // 5
0.5, -0.5, 0.5, // 6
0.5, -0.5, -0.5, // 7
// left face
-0.5, 0.5, -0.5, // 8
-0.5, 0.5, 0.5, // 9
-0.5, -0.5, 0.5, // 10
-0.5, -0.5, -0.5, // 11
// back face
0.5, 0.5, 0.5, // 12
-0.5, 0.5, 0.5, // 13
-0.5, -0.5, 0.5, // 14
0.5, -0.5, 0.5, // 15
// top face
0.5, 0.5, -0.5, // 16
-0.5, 0.5, -0.5, // 17
0.5, 0.5, 0.5, // 18
-0.5, 0.5, 0.5, // 19
// bottom face
0.5, -0.5, -0.5, // 20
-0.5, -0.5, -0.5, // 21
0.5, -0.5, 0.5, // 22
-0.5, -0.5, 0.5, // 23
};
static GLuint indices[] = {
20, 23, 22,
23, 21, 20,
16, 19, 18,
19, 17, 16,
12, 14, 15,
14, 13, 12,
8, 10, 11,
10, 9, 8,
4, 6, 7,
6, 5, 4,
0, 2, 3,
2, 1, 0
};
This is how i'm drawing everything:
for (int x = 0; x < 50; x++)
{
for (int z = 0; z < 50; z++)
{
camera.Model = translate(mat4(1.0), vec3(x, 0, z));
glUniformMatrix4fv(matrixID, 1, GL_FALSE, &(camera.Projection * camera.View * camera.Model)[0][0]);
glDrawElements(GL_TRIANGLES, sizeof(indices), GL_UNSIGNED_INT, 0);
}
}
These are my buffers:
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
GLuint indicesbuffer;
glGenBuffers(1, &indicesbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
How would I fix this?
| Your mesh definition lacks consistency. Taking your 'top' face as an example, one of your triangles is defined in clockwise (CW) order, the other is counter-clockwise (CCW):
You should fix that. Stick to CCW throughout:
Adding to that, some of your face vertices are numbered in a C order, some are in Z order. This isn't a problem per se, but makes it more confusing.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.