question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,012,280 | 70,171,560 | How to pass a vector by reference in pybind11 & c++ | I try to pass vector/array by reference from python through pybind11 to a C++ library. The C++ library may fill in data. After the call to C++, I hope the python side will get the data.
Here is the simplified C++ code:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
class Setup
{
public:
Setup(int version) : _version(version) {}
int _version;
};
class Calculator
{
public:
Calculator() {}
static void calc(const Setup& setup, std::vector<double>& results) { ... }
}
namespace py = pybind11;
PYBIND11_MODULE(one_calculator, m) {
// optional module docstring
m.doc() = "pybind11 one_calculator plugin";
py::class_<Setup>(m, "Setup")
.def(py::init<int>());
py::class_<Calculator>(m, "Calculator")
.def(py::init<>())
.def("calc", &Calculator::calc);
}
On the python side, I intend to:
import os
import sys
import numpy as np
import pandas as pd
sys.path.append(os.path.realpath('...'))
from one_calculator import Setup, Calculator
a_setup = Setup(1)
a_calculator = Calculator()
results = []
a_calculator.calc(a_setup, results)
results
Apparently the results are not passed back. Is there a neat way to do it?
| Figured out a way:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "Calculator.h" // where run_calculator is
namespace py = pybind11;
// wrap c++ function with Numpy array IO
int wrapper(const std::string& input_file, py::array_t<double>& in_results) {
if (in_results.ndim() != 2)
throw std::runtime_error("Results should be a 2-D Numpy array");
auto buf = in_results.request();
double* ptr = (double*)buf.ptr;
size_t N = in_results.shape()[0];
size_t M = in_results.shape()[1];
std::vector<std::vector<double> > results;
run_calculator(input_file, results);
size_t pos = 0;
for (size_t i = 0; i < results.size(); i++) {
const std::vector<double>& line_data = results[i];
for (size_t j = 0; j < line_data.size(); j++) {
ptr[pos] = line_data[j];
pos++;
}
}
}
PYBIND11_MODULE(calculator, m) {
// optional module docstring
m.doc() = "pybind11 calculator plugin";
m.def("run_calculator", &wrapper, "Run the calculator");
}
Python side
results= np.zeros((N, M))
run_calculator(input_file, results)
This way I also do not expose classes Setup and Calculator to the python side.
|
70,012,617 | 70,013,948 | Get a parameter pack from variable argument | I'm trying to get a parameter pack from the list of arguments passed to a macro.
template<std::size_t N, class T, class... Ts>
constexpr bool myFunctionHelper(const char (&fmt)[N], std::size_t n);
template <std::size_t N, typename... Ts>
constexpr bool myFunction(const char (&fmt)[N]) {
return myFunctionHelper<N, Ts...>(fmt, 0);
}
#define FNC(fmt, ...) \
do { \
static_assert(myFunction<sizeof(fmt), decltype...(__VA_ARGS__)>(fmt), \
"Incorrect arg types"); \
} while (false)
But decltype doesn't work as above (sizeof does though). Is there some method to get the parameter pack?
It works if I pass the args to the myFunction and let compiler deduce the template type, but I can't pass the args further. args need not be constexpr.
Edit:
decltype(arg) gives us the type of arg for any object. Here I'm trying to get the type info of multiple arguments as a parameter pack. If I use decltype(__VA_ARGS__), the build succeeds but it just gives me the type of the last param in the __VA_ARGS__. For eg:
decltype(1, "test", 4.0)
would translate to just float.
There doesn't exists anything like decltype...(args) (sizeof...(__VA_ARGS__) does though).
FNC would be used as follows
FNC("%d, %s, %0.2f\n", 1, "test", 4.0);
| Something along these lines, perhaps (not tested):
template <std::size_t N, typename Tuple, size_t... Is>
constexpr bool myFunction1(const char (&fmt)[N], std::index_sequence<Is...>) {
return myFunction<N, std::tuple_element_t<Is, Tuple>...>(fmt);
}
template <std::size_t N, typename Tuple>
constexpr bool myFunction2(const char (&fmt)[N]) {
return myFunction1<N, Tuple>(fmt, std::make_index_sequence<std::tuple_size_v<Tuple>>{});
}
The macro would do
myFunction2<sizeof(fmt), decltype(std::make_tuple(__VA_ARGS__))>(fmt)
|
70,012,648 | 70,023,729 | Recovering pthread_cond_t & pthread_mutex_t after process termination | Hey there!
I have already looked up similiar problems here, but didn't arrive at a final solution.
In my application, I have two processes running concurrently that need to be synchronized via shared-memory. Currently I'm using a pthread_mutex_t & pthread_cond_t for that purpose which are put into shared-memory.
This is working fine until process A crashes whilst waiting on the condition. If process A is restarted a deadlock(?) happens in which process A waits on the condition and process B is stuck indefinetly at the call to pthread_cond_broadcast.
I read that this may be due to the mutex being in an inconsistent state, but in fact it never seems to be in my program.
I would appreciate if you can tell me if I misunderstood something or if there are alternative approaches on solving this or if it isn't possible at all to guard this case of crashing.
struct Poller
{
private:
std::atomic<bool> waiting;
pthread_mutex_t mtx;
pthread_cond_t cnd;
auto lockMutex() -> void
{
// Recover Mutex if any process locking it died unexpectedly
LOG_DEBUG(info, "AdaptivePoller", "Locking mutex...");
if(pthread_mutex_lock(&mtx) == EOWNERDEAD) {
LOG_DEBUG(info, "AdaptivePoller", "Mutex in inconsistent state.");
if(pthread_mutex_consistent(&mtx) != 0) {
throw std::runtime_error("Mutex could not be brought back into consistent state.");
}
}
}
public:
Poller()
{
waiting = false;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&mtx, &attr);
pthread_mutexattr_destroy(&attr);
pthread_condattr_t attrcond;
pthread_condattr_init(&attrcond);
pthread_condattr_setpshared(&attrcond, PTHREAD_PROCESS_SHARED);
pthread_cond_init(&cnd, &attrcond);
pthread_condattr_destroy(&attrcond);
}
auto wait() -> void
{
lockMutex();
waiting = true;
LOG_DEBUG(info, "AdaptivePoller", "Start waiting...");
while(waiting) {
pthread_cond_wait(&cnd, &mtx);
}
pthread_mutex_unlock(&mtx);
}
auto notify() -> void
{
lockMutex();
waiting = false;
LOG_DEBUG(info, "AdaptivePoller", "Notifying...");
pthread_cond_broadcast(&cnd);
pthread_mutex_unlock(&mtx);
}
};
| As far as I am aware, the POSIX API does not define mechanisms sufficient to make your Poller wholly robust against all process-failure scenarios. But you might achieve a situation you consider an improvement by using a SysV semaphore in place of the condition variable and mutex. Here's an outline:
a semaphore can_proceed provides for threads to block themselves until released. This semaphore has initial value 0, and threads block themselves by attempting to decrement it.
a thread releases the currently-blocked processes by incrementing can_proceed by the number of blocked processes. The SysV semaphore API provides an operation for determining how many that is.
The above is not infallible. At least these cases can occur:
A waiting process W dies after a notifying process N reads a waiter count that includes W, but before W completes its semaphore decrement. This will allow one future waiter to pass through without blocking.
A waiting process W2 arrives in wait() between when a notifying process has incremented can_proceed and when the last of the previously-waiting processes completes its semaphore decrement. It is possible in this case that W2 proceeds immediately instead of some thread W1 that was already waiting at the time of the notification. In this case, W1 would be released by the next notification (unless the same thing happened to it again).
If two processes attempt to notify at about the same time then one could observe a waiter count that reflected processes that had already been released, but had not yet completed their semaphore decrement. The likely outcome is that one or more future processes would pass through wait() without blocking.
Inasmuch as two of those are analogous to spurious return from a CV wait, they could be addressed via a similar predicate-checking idiom. That would be tricky given the fact that there is necessarily a gap between a process completing its semaphore decrement and it acquiring a mutex, but perhaps that could be worked around by using an atomic object, so that no mutex is required.
It is also possible that a process dies in notify() before incrementing can_proceed, such that that notification is ineffective. I don't account that a weakness specific to the suggested scheme.
Note that SysV semaphores do not themselves reside in or require shared memory.
|
70,012,655 | 70,012,701 | How to include multiple header directories in g++ without many -I flags? | I have a project with multiple subfolders under my include folder. For instance:
include/
|-- foo/
|-- foo_header1.h
\-- foo_header2.h
|-- bar/
|-- bar_header1.h
\-- bar_header2.h
|-- root_header1.h
\-- root_header2.h
src/
|-- foo/
|-- foo_source1.cpp
\-- foo_source2.cpp
|-- bar/
|-- bar_source1.cpp
\-- bar_source2.cpp
|-- root_source1.cpp
|-- root_source2.cpp
\-- main.cpp
Curently my Makefile is:
all:
g++ -Iinclude/ -Iinclude/foo -Iinclude/bar -o main src/*.cpp src/foo/*.cpp src/bar/*.cpp
I want a way to make that command "smarter", so I don't hardcode all the folders in my source and include directories (potentially my project will have many folders). I just want some way to specify the root header directory and make g++ find the files recursively.
Does anyone know if I can do that? Maybe using the makefile or some special flag of g++...
| You could just add "-Iinclude" to g++ and include the headers as following
#include <foo/foo_header1.h>
#include <bar/bar_header2.h>
This also eliminates the need to have the foo/bar prefix in the header filename. After renaming, the above simplifies to follows
#include <foo/header1.h>
#include <bar/header2.h>
|
70,012,690 | 70,012,787 | how convert dct = {int : [int, list()]] from Python to C++? | I am re-writing this data structure in Python to c ++.
Writing this code in Python is easy for me, but I have trouble with C ++.
I need to change the "step" in my value and find my pairs through the keys.
In Python, I wrote:
step = 0
dct = {1: [step, list()]}
In c ++, I write like this, but I can not find my pairs with the key and then change the step in them.
pair model:
pair<int, pair<int, deque<int>>> p_p;
p_p.first = 1;
p_p.second.first = 3;
p_p.second.second.push_back(10);
cout << "dict = {" << p_p.first << ": [" << p_p.second.first << ", [" << p_p.second.second[0] << "]]}";
output:
dict = {1: [3, [10]]}
and my goal is to make such a thing with loop:
{
1: [0, []],
2: [0, []],
3: [0, []],
4: [0, []]
}
That I can later call with the key and change my list, like this:
{
1: [1, [5, 1]],
2: [2, [1, 1]],
3: [0, [1, 2, 3, 4]],
4: [0, [1, 17]]
}
How can I use from pair or map?
| Here's a rough C++11 equivalent to the posted Python code:
#include <iostream>
#include <map>
#include <utility> // for std::pair
#include <vector>
int main(int argc, char ** argv)
{
std::map<int, std::pair<int, std::vector<int> > > dct;
int step = 0;
// insert some empty pairs into (dct)
for (int i=1; i<4; i++) dct[i] = std::pair<int, std::vector<int> >();
// add some random data to each entry in (dct)
for (auto & e : dct)
{
const int & key = e.first;
std::pair<int, std::vector<int> > & value = e.second;
int & iVal = value.first;
iVal = rand()%100; // set the first value of the pair to something
std::vector<int> & vec = value.second;
for (int j=rand()%5; j>=0; j--) vec.push_back(rand()%10);
}
// Finally, we'll iterate over (dct) to print out its contents
for (const auto & e : dct)
{
const int & key = e.first;
std::cout << "Key=" << key << std::endl;
const std::pair<int, std::vector<int> > & value = e.second;
std::cout << " value=" << value.first << " /";
for (auto i: value.second) std::cout << " " << i;
std::cout << std::endl;
}
return 0;
}
When I run it, I see output like this:
Key=1
value=7 / 3 8 0 2 4
Key=2
value=78 / 9 0 5 2
Key=3
value=42 / 3 7 9
|
70,012,760 | 70,013,068 | Calling another constructor C++ | I have something like this:
Foo::Foo(vector<item> items) {
// do stuff
}
I'd like to call this constructor from another constructor:
Foo::Foo(char* buf, size_t num) {
// unpack the bytes into vector
Foo::Foo(items);
}
Is this possible in C++ 17+? I know that you can call another constructor using an initialize list, but this seems trickier
| Simply call a delegating constructor. Use a helper function to construct the vector<item>.
namespace {
vector<item> helper(char*buff, size_t num)
{
/* your implementation for re-packaging the data here */
}
}
Foo::Foo(char*buff, size_t num)
: Foo(helper(buff,num))
{}
|
70,012,841 | 70,013,373 | How are objects from derived classes constructed in C++ | Im not a C++ pro, i've done mostly Java and C#. A teacher said something that confused me today. I've tried to validate the info by doing some research, but i ended up even more confused.
Lets say i have class A and class B. Class A is the base class and B is derived from A.
Now i already know that when an object of class B is made, the constructor from class A is called, and then the constructor from classe B is called. Similarly, when and object of class B is destroyed, the class B destructor is called, and then the ones from class A.
So far, my understanding was that Class B contains everything from class A except it's constructors and destructors. I thought that when an object from class B was built, only one object (of both types A and B) was created in memory.
Now my teacher is saying that when B is built, 2 separate objets are created and somehow "linked" together: one of class A and then one of class B. Both objects would exist in memory until the destruction of the class B object is called. Then the class B objet would be destroyed before the class A object is destroyed.
Which one is correct?
ps sorry if my english is so-so, it's not my native language...
Edit: ill try to rephrase:
I think: Class B contains all attributes and methods of class A. When i create an object from class B, only 1 object exists in memory. The constructor of class A is called just to initialize the part of my object that was originally from class A.
The teacher said: When i create an object from class B, 2 objects are created in memory. When i command the destruction of my object, the class B object that is in memory is destroyed first, and then the class A object that is also remaining in memory is destroyed. The teacher was never able to clarify how the class B object is able to use the methods and attributes of the class A object.
For me, this also seems to imply that there is a "ghost object" somewhere in memory that i am unaware of and of which i have almost no control.
| According to http://www.vishalchovatiya.com/memory-layout-of-cpp-object/#Layout_of_C_Object_With_Inheritance
These two classes:
class X {
int x;
string str;
public:
X() {}
virtual ~X() {}
virtual void printAll() {}
};
class Y : public X {
int y;
public:
Y() {}
~Y() {}
void printAll() {}
};
Would be represented in memory so that the memory layout of Y contains the data members of the base class followed by the data members of the derived class:
| |
|------------------------------| <------ Y class object memory layout
| int X::x |
stack |------------------------------|
| | int string::len |
| |string X::str ----------------|
| | char* string::str |
\|/ |------------------------------| |-------|--------------------------|
| X::_vptr |------| | type_info Y |
|------------------------------| |--------------------------|
| int Y::y | | address of Y::~Y() |
|------------------------------| |--------------------------|
| o | | address of Y::printAll() |
| o | |--------------------------|
| o |
------|------------------------------|--------
| X::X() |
|------------------------------| |
| X::~X() | |
|------------------------------| |
| X::printAll() | \|/
|------------------------------| text segment
| Y::Y() |
|------------------------------|
| Y::~Y() |
|------------------------------|
| Y::printAll() |
|------------------------------|
| string::string() |
|------------------------------|
| string::~string() |
|------------------------------|
| string::length() |
|------------------------------|
| o |
| o |
| o |
| |
That same page also has memory layouts of other scenarios, including multiple inheritance and virtual inheritance.
|
70,013,032 | 70,014,400 | C vs C++ why is this macro not expanded to a constant? | I am using gcc/g++. The below code compiles fine with gcc -S test.c, however with g++ -S test.cpp I get error: requested alignment is not an integer constant. If I look at the preprocessor output for both it looks identical. So my question is why isn't ALIGN_BYTES being evaluated to the constant 64 by the preprocessor in the C++ case? (If I replace ALIGN_BYTES with the constant 64 it works fine)
/* test.c, test.cpp */
#define BITS 512
#define ALIGN_BYTES (BITS / 8)
#define ALIGN __attribute__ ((aligned(ALIGN_BYTES)))
typedef char* ALIGN char_PT;
| It is not a macro expansion issue. The macro is not expanded to a constant in either C or C++, here. The preprocessor does not do arithmetic, so it simply generates the expression 512 / 8 which isn't a constant, but which the compiler should definitely be able to reduce to one.
The preprocessor generates the same code for C and C++ here, but GCC (for reasons I do not understand) treats the __attribute__ extension differently in the two languages. I really have no idea why, there likely are good reasons, but someone else will have to explain that.
If you compile C, gcc is happy with aligned((512 / 8)), but if you compile C++ with g++ it will complain that 512 / 8 is not a constant. It is right, I guess, but really also wrong.
There are other cases where it is the opposite, where g++ is happy with a non-constant, but gcc is not. If you declare a static const int for example, you can use it in __attribute__((aligned(...)) in C++ but not in C. Again, I cannot explain why. It's a compiler extension and GCC can do whatever. And for some reason, it will treat the two languages differently here.
/* g++ will complain about this one; gcc will not */
typedef char *__attribute__((aligned((512 / 8)))) char_PT;
/* gcc will complain about this one; g++ will not */
static const int A = 16;
typedef char *__attribute__((aligned(A))) char_PT2;
I suppose, though, that since we know one version that works with C and another that works with C++, we could do this:
#define BITS 512
#ifdef __cplusplus
static const unsigned int ALIGN_BYTES = BITS / 8;
#define ALIGN __attribute__((aligned(ALIGN_BYTES)))
#else /* C */
#define ALIGN_BYTES (BITS / 8)
#define ALIGN __attribute__((aligned(ALIGN_BYTES)))
#endif
typedef char *ALIGN char_PT;
|
70,013,098 | 70,013,155 | C++ template function explicit specialization with multiple template types | I'd like to write a templatized function with two template types: one a bool and one a typename, and I'd like to specialize on the typename.
eg, this is what I want, but specialized on just a couple types for T:
template<bool b, typename T>
void foo(T val)
{
// do different stuff based on b and type of T.
}
without the bool in there, I can do something like this:
template<typename T>
void bar(T val) {
static_assert(false, "not implemented");
}
template<>
void bar<short>(short val) {
printf("it's a short!\n");
}
I can't figure out the syntax for this, and the microsoft docs on specialization only cover the single-type case.
| template<bool B, typename T>
void foo(T const&)
{
static_assert(false, "not implemented");
}
template<bool B>
void foo(short)
{
printf("it's a short!\n");
}
However, this is not really specialisation, but overloading, which is completely appropriate. In fact, you could omit the general case.
|
70,014,236 | 70,014,369 | Can I create a function which takes any number of arguments of the same type? | So basically, I want to create a function like this:
total_sum(1, 2, 5, 4, 2) // return 14
total_sum(5, 6, 2) // return 13
One way that I can use is ellipsis, something like this:
#include <cstdarg>
int total_sum(int count, ...)
{
int sum{0};
va_list list;
va_start(list, count);
for (int arg{0}; arg < count; ++arg)
{
sum += va_arg(list, int);
}
va_end(list);
return sum;
}
But when I call total_sum(), I have to provide an extra argument. So in the example, I have to call:
total_sum(5, 1, 2, 5, 4, 2);
total_sum(3, 5, 6, 2);
which I don't really like. Also, ellipsis is really prone to error, so I want to stay away from them.
Another way I can think of is using some container:
#include <vector>
int total_sum(std::vector<int> values)
{
int sum{0};
for(const auto &i : values)
{
sum += i;
}
return sum;
}
and I call it like:
total_sum({1, 2, 5, 4, 2});
total_sum({3, 5, 6, 2});
But, I want to not have those curly braces, so what can I do? Is there some C++ feature that allows me to do this?
Some relevant links: restrict variadic template arguments, fold expression, parameter packs and a
C++11 "equivalent" of fold expressions
| Use C++17 fold expression:
template<class... Args>
constexpr auto total_sum(const Args&... args) {
return (args + ... + 0);
}
static_assert(total_sum(1, 2, 5, 4, 2) == 14);
static_assert(total_sum(3, 5, 6, 2) == 16);
|
70,015,322 | 70,015,821 | Efficient lookup on fixed collection of vectors | I have a fixed number (5) of vectors of structs (structs are inserted at runtime, a number can vary).
And i have a enum class which is used as a key for lookup. E.g.
enum class CountryCode {
kUS,
// ...other 4
};
const std::vector<SomeStruct>& get_by_country_code(CountryCode cc);
I can use std::unordered_map<CountryCode, std::vector<SomeStruct>, CustomHash> with custom hash, but i think it not worth it for fixed size collection, which ordering is known before runtime.
What would be the most efficient way to store these 5 vectors and do a lookup by the enum value?
I'm also thinking about std::tuple but in my case values are not heterogeneous.
|
What would be the most efficient way to store these 5 vectors and do a lookup by the enum value?
An array. The default values of enum are 0,1,... which fit perfectly as the indices of an array.
Only small hurdle is that enum classes must be explicitly converted to the underlying integer.
does array of vectors considered a good practice?
There's nothing particularly bad practice about them.
If the sizes of the vectors are known at the same time and they don't vary after creation, then there is a more efficient solution: Use a single vector that contains all objects partitioned by the country code. Then use an array of spans to the subvectors.
|
70,015,481 | 70,015,690 | How do I count leading zeros on both mac M1 and x86-64? | Originally I tried lzcnt but that doesn't seem to work on a mac. I'm working with someone who is using the apple M1 CPU which is ARM64v8.4
In this arm document which list ARM 8 it appears clz supports using 0
CLZ Xd, Xm
Count Leading Zeros (64-bit): sets Xd to the number of binary zeros at the most significant end of Xm. The result will be in the range 0 to 64 inclusive.
The CPU we originally support is x86-64 which has _lzcnt_u64
Both instructions appear to return 64 if the value is 0. Specifically "0 to 64 inclusive" on ARM and the intel site suggest it too (and confirmed by my code)
However GCC says the below
Built-in Function: int __builtin_clzll (unsigned long long)
Similar to __builtin_clz, except the argument type is unsigned long long.
Can I safely use 0 or does this builtin use a different instruction? I tried on clang and the sanitizer stop the program and told me it is a problem which was surprising to me.
How should I get the leading zero count when I want to get 64 if I pass in 0 like these two instructions do
| If C++20 features are available, std::countl_zero<T> solves the problem, and it's up to compiler devs to implement it in a way that compiles efficiently even for an input of zero. (In which case it's required to return the number of value-bits in the integer type you passed, unlike __builtin_clzll)
That's great in theory, but unfortunately they're faced with the same problem you are of using actual builtin functions. libstdc++ just uses x ? __builtin_clzll(x) : 64 more or less, which GCC doesn't optimize even when a hardware instruction is available that produces 64 for an input of 0. (See below C++ and asm code blocks.)
So in practice std::countl_zero<uint64_t> always compiles to multiple instructions with GCC even on machines like ARM64 always, or x86-64 even when lzcnt is known at compile-time to be available (-mlzcnt or -mbmi). clang does optimize away the ternary.
__builtin_clzll will compile to 63-bsr(x) on x86 if you don't use a -march= option that includes BMI1 (or for some AMD, at least LZCNT without the rest of BMI1). BSR leaves its destination unmodified for an input of 0, not producing -1 or something. https://www.felixcloutier.com/x86/bsr (This was probably a big part of the motivation of defining the builtin that way, so it can just compile to a single BSR or BSF instruction without conditional branches or cmov on x86 long before lzcnt existed. Some use-cases don't need to use it with zero.)
What's the goal here, portable GNU C++? Or perfectly optimized asm for a couple of compile targets with specific options?
You could try x ? __builtin_clzll(x) : 64 and hope GCC optimizes that to x86-64 lzcnt when available. clang does do this optimization, but unfortunately GCC11 doesn't. (Godbolt)
unsigned clz(unsigned long long x) {
return x ? __builtin_clzll(x) : 64;
}
BTW, libstdc++'s std::countl_zero compiles the same way, presumably because it's written more or less like that. (Probably with some std::numeric_limits<T> stuff instead of a hard-coded 64).
# x86-64 clang 13 -O3 -march=haswell
clz(unsigned long long):
lzcnt rax, rdi
ret
x86-64 GCC 11.2 -O3 -march=haswell
clz(unsigned long long):
xor edx, edx # break output dependency for lzcnt on Intel pre-SKL
mov eax, 64
lzcnt rdx, rdi
test rdi, rdi
cmovne eax, edx # actually do the ternary
ret
Same story for ARM64: clang optimizes away the redundant selection operation to just clz, GCC doesn't:
# ARM64 gcc11.2 -O3 -march=cortex-a53
clz(unsigned long long):
cmp x0, 0
clz x0, x0
mov w1, 64
csel w0, w0, w1, ne
ret
Explicitly use lzcnt when available:
#ifdef __BMI__
#include <immintrin.h>
unsigned clz_lzcnt(unsigned long long x) {
return _lzcnt_u64(x);
}
#endif
# x86-64 GCC11 -O3 -march=haswell
clz_lzcnt(unsigned long long):
xor eax, eax
lzcnt rax, rdi
ret
(So really you'd want to use this #ifdef inside another function, with a #else using the ternary as a fallback.)
|
70,015,603 | 70,024,650 | Overloading a parent member function without ref-qualifier with a child member function with ref-qualifier in C++ | In C++ one cannot overload in one class a member function with ref-qualifier with a member function without ref-qualifier. But at the same time it is possible to inherit one member function from a parent class and overload it in a child class as in the example:
struct A {
void f() {}
//void f() & {} //overload error everywhere
};
struct B : A {
using A::f;
void f() & {} //ok everywhere
};
int main() {
B b;
b.f(); //ok in GCC only
}
Only during the invocation of f, Clang complains that call to member function 'f' is ambiguous. But GCC accepts the program without any error, demo: https://gcc.godbolt.org/z/5zzbWcs97
Which compiler is right here?
| GCC is correct to accept this, but the situation changed recently. The current phrasing is that a using-declaration in a class ignores (base-class) declarations that would be ambiguous (in a sense that is more strict than for overload resolution, partly because there is no argument list yet) with other declarations in the class. void() and void() & members are ambiguous in this sense, so b.f finds only B’s f and the call is valid.
In previous (as of this writing, that means “published”) versions of the standard, both functions would be made available because the & distinguished them (in a sense that is even stricter), which would not only render the call ambiguous (as Clang says) but be ill-formed outright because the base- and derived-class functions were checked for overload compatibility which they lack.
|
70,015,825 | 70,016,028 | Copy constructor not used during pass by value in C++ | class A {
int x;
public:
A() { cout << "\t A() \n"; }
A(int _x): x(_x) { cout << "\t A(int) \n"; }
A(const A& other): x(other.x) { cout << "\t A(const A&) \n"; }
A(A&& other): x(std::move(other.x)) { cout << "\t A(A&&) \n"; }
A& operator=(const A& other) { x = other.x; cout << "\t operator=() \n"; return *this; }
};
void func_1(A obj) {
cout << "func_1\n";
}
A func_7(const A& obj) {
cout << "func_7\n";
return obj;
}
int main() {
A obj_1; // stdout: "A()" [OK]
A obj_2 = 10; // stdout: "A(int)" [OK]
A obj_3 = obj_2; // stdout: "A(const A&)" [OK]
A obj_4 = std::move(obj_3); // stdout: "A(A&&)" [OK]
obj_4 = obj_2; // stdout: "operator=()" [OK]
func_1(obj_1); // stdout: "A(const A&) \n func_1" [OK]
func_1(A(5)); // stdout: "A(int) \n func_1" [!?] Copy constructor?
func_1(5); // stdout: "A(int) \n func_1" [!?] Copy constructor?
A obj_7 = func_7(obj_2); // stdout: "func_7 \n A(const A&)" [!?] Copy constructor?
return 0;
}
For func_1(A(5));, I expected the output to be A(int) \n A(const A&) \n func_1 because we are passing A(5) by value so the passed object should be copied to the parameter. Similarly for func_1(5);.
For A obj_7 = func_7(obj_2);, I expected the output to be func_7 \n A(const A&) \n A(const A&) because we are returning an object so that object should be copied on the stack first and then the copy constructor will be used to declare obj_7 using the returned object.
Am I missing something here? I am aware of the return value optimization, but I don't think that will apply in both the functions that we have here.
|
For func_1(A(5));, I expected the output to be A(int) \n A(const A&) \n func_1 because we are passing A(5) by value so the passed object should be copied to the parameter.
You expected wrongly. A(5) is a prvalue of the same type, so the temporary object will not be materialised, and its initialiser is instead used to initialise the parameter that would have been initialised by the non-materialised temporary.
Similarly for func_1(5);.
The class has an implicit converting constructor that accepts an integer. You pass an integer; the converting constructor is used to initialise the parameter.
For A obj_7 = func_7(obj_2);, I expected the output to be func_7 \n A(const A&) \n A(const A&) because we are returning an object so that object should be copied on the stack first and then the copy constructor will be used to declare obj_7 using the returned object.
The reason for this is similar as the first case. The function call is a prvalue.
|
70,016,007 | 70,019,500 | Inputting multiple integers from lines into a 2d array c++ | I initialized a 2d array and am trying to fill the array respectively. My issue is I cannot get the 2d array to update.
Input is:
0 1 9
0 4 8
1 5 5
2 0 6
3 2 2
1 3 1
2 1 3
4 3 7
5 3 4
My code is:
stringstream s(input);
while(count != numV){
getline(cin, input);
while(s >> u >> v >> weight)
Graph[u][v] = weight;
count++;
}
| Note that you don't have to use arrays for storing the information(like int values) in 2D manner because you can also use dynamically sized containers like std::vector as shown below. The advantage of using std::vector is that you don't have to know the number of rows and columns beforehand in your input file. So you don't have to allocate memory beforehand for rows and columns. You can add the values dynamically. The below program read data(int values) from input.txt and store those in a 2D vector.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
std::string line;
int word;
std::ifstream inFile("input.txt");
//create/use a std::vector instead of builit in array
std::vector<std::vector<int>> vec;
if(inFile)
{
while(getline(inFile, line, '\n'))
{
//create a temporary vector that will contain all the columns
std::vector<int> tempVec;
std::istringstream ss(line);
//read word by word(or int by int)
while(ss >> word)
{
//std::cout<<"word:"<<word<<std::endl;
//add the word to the temporary vector
tempVec.push_back(word);
}
//now all the words from the current line has been added to the temporary vector
vec.emplace_back(tempVec);
}
}
else
{
std::cout<<"file cannot be opened"<<std::endl;
}
inFile.close();
//lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
for(std::vector<int> &newvec: vec)
{
for(const int &elem: newvec)
{
std::cout<<elem<<" ";
}
std::cout<<std::endl;
}
return 0;
}
The output of the above program can be seen here. The input file through which int values are read is also given at the above mentioned link.
If you want to take input using std::cin instead of std::ifstream then you just need to change the line while(getline(inputFile, line, '\n')) to :
while(getline(std::cin, line, '\n'))
And also remove other references to inputFile. The logic remains the same. IMO reading from file saves time and effort since the user don't have to write the inputs again and again into the console.
|
70,016,284 | 70,023,063 | Make script in Unity to Unreal | Im new to Unreal. I tried to follow the tutorial into making A* pathfinding:
https://www.youtube.com/watch?v=nhiFx28e7JY&t=1252s&ab_channel=SebastianLague
I don't really know how to change the script made in Unity to Unreal.
UnityScript
public class Node {
public bool walkable;
public Vector3 worldPosition;
public Node(bool _walkable, Vector3 _worldPos) {
walkable = _walkable;
worldPosition = _worldPos;
}
}
My UnrealScript:
USTRUCT(BlueprintType)
struct FAS_Node
{
GENERATED_USTRUCT_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category= "Nodes")
FVector worldPosition;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category= "Nodes")
bool walkable;
Node(bool _walkable, FVector _worldPos){
walkable = _walkable;
worldPosition = _worldPos;
}
};
it return error saying Node doesnt have return type
| I guess you cannot create constructors with parameters in such way in UE4. Try define a default constructor.
If you really need to pass parameters to it - check ObjectInitializer constructor here: https://ikrima.dev/ue4guide/engine-programming/uobjects/new-uobject-allocation-flow/
|
70,016,304 | 70,016,391 | In TCP/IP Socket send, Send data still remains in OS Memory | I created a simple chatting client program to communicate with the server.
After the client sent data to the server using the send() function, the data was initialized to memset (buf, 0x00, sizeof(buf)), but after searching OS memory through Dumpit, there are still traces of data sent somewhere.
How can i clear send data?
int main() {
WSADATA wsaData;
SOCKET hSocket;
SOCKADDR_IN servAddr;
char message[30];
char tmp[8];
int strLen;
memset(tmp, 0x00, 8);
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
ErrorHandling("WSAStartup() error!");
hSocket = socket(PF_INET, SOCK_STREAM, 0);
if (hSocket == INVALID_SOCKET)
ErrorHandling("socket() error!");
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr("222.106.99.137");
servAddr.sin_port = htons(atoi("20071"));
if (connect(hSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
ErrorHandling("connect() error!");
memcpy(tmp, "thisishell", 7);
sendto(hSocket, tmp, strlen(tmp) + 1, 0,
(struct sockaddr*)&servAddr, sizeof(servAddr));
memset(tmp, 0x00, 8);
memset(tmp, 0xFF, 8);
memset(tmp, 0x00, 8);
closesocket(hSocket);
WSACleanup();
return 0;
}
| Your binary program code still contains the string literal thisishell. Most likely, that's what you're seeing, because your other string literals like "connect() error!" can be seen right above it in memory.
|
70,016,345 | 70,018,021 | C# pass struct with interface to unmanaged C++ | I have an unmanaged C++ DLL and some C# code that uses [dllimport] to access it. I have a struct that derives from an interface (say Dog : Animal) and on the C++ side I have a class that derives from an abstract class (say Dog : public Animal). I want to have a C++ function that somehow takes in Animal as a parameter, so that I can pass Dog from C# (since you can't use abstract classes as parameters in C++).
| One option would be to use c++/cli to define your object model. That would make it usable by both c# and c++/cli code.
P/invoke essentially does method calls the same way C does. This means they are highly compatible between different languages, but also that they do not support things like polymorphism.
A struct is essentially just a chunk of data in both C# and C, you just need to ensure the layout is the same. But as soon as you start to involve inheritance things become much more complicated since c# and c++ represent objects in completely different ways.
That said, you could still create a c++ method that takes a dog-structure from c# and converts this to the equivalent c++ type.
|
70,016,357 | 70,016,734 | Can you detect template member of a class using std::is_detected | I use std::experimental::is_detected to determine if class has certain member functions:
#include <utility>
#include <experimental/type_traits>
template<typename USC>
class Descriptor
{
private:
template<class T>
using has_member1_t =
decltype(std::declval<T>().member1(std::declval<std::vector<char> &>()));
public:
static constexpr bool has_member1 =
std::experimental::is_detected_convertible_v<long long,
has_member1_t,
USC>;
};
The problem is I also need to determine if class has certain template member function with following signature:
template<typename Derived>
int member2(Eigen::ArrayBase<Derived> &&)
I've tried to do it like so:
//Inside Descriptor
template<class T, class U>
using has_member2_t =
decltype(std::declval<T>().member2(std::declval<Eigen::ArrayBase<U> &&>()));
static constexpr bool has_member2 =
std::experimental::is_detected_convertible_v<long long,
has_member2_t,
USC>;
but it doesn't work. As I'm not really experienced with C++ TMP I would like to know is there a way to achieve this with std::experimental::is_detected or some other utility?
| If c++20 is an option, this kind of code has been made a lot easier to both read and write by using concepts.
#include <iostream>
#include <vector>
struct Foo {
int member1(int) {
return 1;
}
template <typename T>
double member2(std::vector<T>) {
return 2.5;
}
};
struct Bar {};
template <typename T>
concept MyConcept = requires (T t) {
{ t.member1(0) } -> std::same_as<int>; // We can check return type
{ t.template member2<int>(std::vector<int>{}) }; // but we don't have to
};
int main() {
static_assert(MyConcept<Foo>);
static_assert(!MyConcept<Bar>);
}
The issue with your attempt is that you are not passing anything as U for the check. I would also modify it to use the .template member2<...> syntax to explicitly check for a template.
Here is an example of that.
#include <iostream>
#include <vector>
#include <utility>
#include <experimental/type_traits>
struct Foo {
int member1(int) {
return 1;
}
template <typename T>
double member2(std::vector<T>) {
return 2.5;
}
};
struct Bar {};
template<class T, class U>
using has_member2_t =
decltype(std::declval<T>().template member2<U>(std::declval<std::vector<U> &&>()));
int main() {
static constexpr bool has_member2_Foo =
std::experimental::is_detected_convertible_v<long long,
has_member2_t,
Foo, double>;
static constexpr bool has_member2_Bar =
std::experimental::is_detected_convertible_v<long long,
has_member2_t,
Bar, double>;
static_assert(has_member2_Foo);
static_assert(!has_member2_Bar);
}
|
70,016,562 | 70,016,752 | c++ frequently open and close iostream will affect IO performance? | If I want to write into a file frequently like the function of logging, which is the better way?
when I need to write, open iostream and close when it is done
void log(const string& s){
iostream ios(log_path);
ios << s;
ios.close();
}
void main(){
while (need_to_log) {
log(some_string);
}
}
save the file descriptor as some global variable at the beginning, use it when needed to write and close when program closes.
iostream ios(log_path);
void log(const string& s){
ios << s;
}
void main(){
while (need_to_log) {
log(some_string);
}
ios.close();
}
Will there be a significant performance difference between those two?
| Yes, there will probably be a significant difference – if logging is what your application is spending most of its time on.
To open and close files requires a system call. To close a file, in particular, requires the internal buffer of the ostream to be flushed, which requires another system call, and possibly also writing to a relatively slow disk.
In contrast, if you keep the stream open, operator<< just writes to an internal buffer in memory, and only writes it out when the buffer gets full. This is more efficient, but it also means you might see a delay in log lines appearing in the file. Send std::flush into the stream to flush earlier; note that writing std::endl (as opposed to simply '\n') also triggers a flush.
|
70,016,665 | 70,016,740 | Doesn't instance call function to variadic template | I have write function to deduce how much parameters I forward to function. Something like this:
template<typename Arg>
constexpr size_t get_init_size(Arg arg, size_t i) {
return i + 1;
}
template<typename T, typename ... Args>
constexpr size_t get_init_size(T First_arg, Args ... args, size_t i) {
return get_init_size(args... , i + 1);
}
auto create_ipv4_header() {
size_t x = get_init_size(0b01, 0b10, 0b01, static_cast<size_t>(0));
return x //<= must return 3
}
But compiler write:
error: no matching function for call to 'get_init_size(int, int, int, size_t)'
So it is problem in variadic template? And one more thing if I change variadic template to something like this:
template<typename T, typename ... Args>
constexpr size_t get_init_size(T First_arg, Args ... args, size_t i = 0)
I can put down last parameter?(I doesn't test it with variadic template) Thanks for help!
| You don't need to write a recursive template function to do this, you can use the sizeof...() operator on the type of the parameter pack to get the number of elements directly:
template<typename... Args>
constexpr std::size_t get_init_size(Args&&...) {
return sizeof...(Args);
}
See it in action here.
The reason why your function doesn't work is because a parameter pack is deduced greedily; meaning Args... args matches 0b10, 0b01 and static_cast<size_t>(0). Then because there is no argument matching the size_t i anymore, substitution fails and the only candidate left is the first version of get_init_size(), which of course also is not a match. It's always hard or impossible to have extra parameters after a parameter pack. You could move size_t i to the front though. Another approach is to not pass i as a parameter, but add + 1 to the return value instead:
template<typename Arg>
constexpr std::size_t get_init_size(Arg&&) {
return 1;
}
template<typename T, typename... Args>
constexpr std::size_t get_init_size(T&&, Args&&... args) {
return get_init_size(args...) + 1;
}
|
70,016,727 | 70,045,895 | Signal handlers of C++ application within a docker container are not working | I have the following C++ code:
#include <signal>
#include <iostream>
void sig_handler(int signo, siginfo_t *info, void *_ctx) {
cout << "HANDLE AND RESET!!" << endl;
// try to forward the signal.
raise(info->si_signo);
// terminate the process immediately.
puts("watf? exit");
_exit(EXIT_FAILURE);
}
void registerSignalHandlers() {
vector<int> signals = {
// Signals for which the default action is "Core".
SIGABRT, // Abort signal from abort(3)
SIGBUS, // Bus error (bad memory access)
SIGFPE, // Floating point exception
SIGILL, // Illegal Instruction
SIGIOT, // IOT trap. A synonym for SIGABRT
SIGQUIT, // Quit from keyboard
SIGSEGV, // Invalid memory reference
SIGSYS, // Bad argument to routine (SVr4)
SIGTRAP, // Trace/breakpoint trap
SIGXCPU, // CPU time limit exceeded (4.2BSD)
SIGXFSZ, // File size limit exceeded (4.2BSD)
SIGTERM
};
for (size_t i = 0; i < signals.size(); ++i) {
struct sigaction action;
memset(&action, 0, sizeof action);
action.sa_flags = static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND);
sigfillset(&action.sa_mask);
sigdelset(&action.sa_mask, signals[i]);
action.sa_sigaction = &sig_handler;
int r = sigaction(signals[i], &action, nullptr);
}
}
int main(int argc, char *argv[]) {
registerSignalHandlers();
//rest of the code goes here
return 0;
}
I run my application within a docker container with debian:stretch image with tini as the PID 1 (used it directly not through bash). When I run the container on my device (MacBook Pro) everything works fine with no issues at all. I try to cause segmentation fault SIGSEGV exception within my code to test the handler trigger, on my device, it's working perfectly but once I run the same exact container on the server (CentOS 7) the handler is not working at all.
What I mean by not working at all is the signal is never received by my application. I've tried to send the signal manually from inside the container kill -15 PID_OF_APPLICATION and the handler worked just fine as it should but if send kill -11 PID_OF_APPLICATION the handler doesn't work and no idea why!
I tried to check if the signal is being raised by my code using strace and I was able to see that SIGSEGV is raised.
Also, I tried to run a script that runs my application and trap the signal received by it. The signal was received in the script and but also the handler was not triggered too
I'm not sure if I'm missing something related to a configuration of the docker container (I'm using docker-compose) but I think I'm doing everything correctly since the same docker-compose file on my device is starting the container and it's working with no issues.
Are the signal raised by the application within the container handled through the PID 1 too? tini in my case.
Any help is highly appreciated
UPDATE
If I set the entrypoint to sleep infinity and I get inside the docker container with docker exec -it container_id bash then start my application manually as foreground process the handlers works with no problems
| I've been there before. It's a real struggle especially when things work on your device but it's not on other devices.
I'll write the steps I did for my own problem and maybe it can light up some solutions for you.
Things were working perfectly on macOS and I had to compare the docker engine versions between my device and the server which was CentOS7 but no difference!
Then I tried to run the same docker image using docker-compose on Ubuntu instead of CentOS7 and here is the surprise! it was working too, so my problem was only on CentOS7. I would recommend you do the same, try to run your docker image on another OS like Ubuntu just to make sure that's your problem not related to your actual application.
Try to run your app with a cronjob
Yes, try to run it as a cronjob. I'm not sure about the problem's root cause but this worked for me. I think it's related to how docker proxy signals when you run the container Here you will find at the end of the README file a useful conclusion about signals depending on how you run your container.
Also, another possible reason is when the application is running in the background the signals somehow are not proxied to it, so running it as a cronjob would be different from a regular background process.
You can manage this approach as a full solution with maintaining the docker container responses to your app (including the crash) as follows:
Use tini as the entrypoint of your container.
Make tini runs your script as CMD
Your script will update the crontab file with your cronjob (it's up to you to define the frequency of run)
The added cron would run your actual run script.
Your run script should have a trap function. Why? once your app is crashed you can send a KILL signal to your entrypoint script (point #2) which will kill the docker container. This way you maintained the behaviour of running your app as an entrypoint.
Hope this is helpful for your case.
|
70,016,814 | 70,018,399 | Can two different processes communicate with each other using Windows events in WINAPI? | I am in the midst of developing two applications that communicate using a file. These applications are running on the same machine. To be clear, I have a writer.exe and a reader.exe executables.
The writer.exe constantly writes a random integer to a common file "some_file.bin" and closes the file. It repeats the same process again: opens the file, writes random int and closes it. This is done in a while loop.
The reader.exe is constantly reading the file "some_file.bin", printing the read integer to its console.
Both of these applications are written in C++ using the std::fstream class for file I/O.
So far, this is not working properly, because we have a race condition happening here.
I want some way to properly communicate between these two processes, using Win32 Events, so that the writer.exe process knows to wait until the reader.exe process has finished reading, and the reader.exe process knows to pause until the writer.exe process has finished writing.
I'm hoping to do this using the CreateEvent, WaitForSingleObject family of API calls present natively on the Windows platform.
Please feel free to tell me if this is possible between two processes?
So far, I have only found examples using the above APIs to signal threads of one main process... ?
| Yes, it is possible. When one process creates a handle to an Event object, you have the option of assigning a name to that object in the kernel. The other process can then create/open its own handle to that Event object using the same name.
Note that to accomplish what you want, you actually would need 2 Events, eg:
writer.exe:
HANDLE hReadable = CreateEvent(NULL, FALSE, FALSE, TEXT("ReaderCanRead"));
if (!hReadable) ...
HANDLE hWritable = CreateEvent(NULL, FALSE, TRUE, TEXT("WriterCanWrite"));
if (!hWritable) ...
...
while (!quit)
{
...
WaitForSingleObject(hWritable, INFINITE);
if (quit) break;
// write int...
SetEvent(hReadable);
...
}
reader.exe:
HANDLE hReadable = CreateEvent(NULL, FALSE, FALSE, TEXT("ReaderCanRead"));
// or: HANDLE hReadable = OpenEvent(SYNCHRONIZE, FALSE, TEXT("ReaderCanRead"));
if (!hReadable) ...
HANDLE hWritable = CreateEvent(NULL, FALSE, TRUE, TEXT("WriterCanWrite"));
// or: HANDLE hWritable = OpenEvent(EVENT_MODIFY_STATE, FALSE, TEXT("WriterCanWrite"));
if (!hWritable) ...
...
while (!quit)
{
...
WaitForSingleObject(hReadable, INFINITE);
if (quit) break;
// read int...
SetEvent(hWritable);
...
}
That being said, you might consider using a named block of shared memory via CreateFileMapping()+MapViewOfFile(), rather than using a physical file.
However, there are many other Inter-Process Communication mechanisms that are way more suitable to your producer/consumer model than using a shared file/memory protected by Events. Pipes, sockets, mailslots, even window messages, would be a much better choice.
|
70,016,827 | 70,016,942 | How do I create two classes that refer to each other in different header files? | I have two classes in two different header files. I, as advised in another topic with a similar question, declared class A before class B and declared class B before class A. But it did not help. Seller still can't see the Organization
Seller.h
#ifndef OOP_3_SELLER_H
#define OOP_3_SELLER_H
#include "Organization.h"
class Organization;
class Seller{
protected:
Organization*owner;
...
};
Organiztion.h
#ifndef ORGANIZATION_OOP3_H
#define ORGANIZATION_OOP3_H
#include "Seller.h"
class Seller;
class Organization{
std::vector<Seller*> own;
...
};
The compiler tells me the following error:
error C2027: use of undefined type 'Organization'. That is, as I understand it, the Organization sees the Seller, but the Seller does not see the Srganization
| Since you've forward declared the class Organization in Seller.h there is no need to write #include "Organisation.h". Similarly, in Organization.h" since you've forward declared class Seller there is no need to write #include "Seller.h". Also, always take into account cyclic dependency like in your program Organization.h has a #include "Seller.h" and then Seller.h has a #include "Organization.h"
The running(successfully compiled) program can be seen here.
Organization.h
#ifndef ORGANIZATION_OOP3_H
#define ORGANIZATION_OOP3_H
//#include "Seller.h"
#include <vector>
class Seller;
class Organization{
std::vector<Seller*> own;
};
#endif
Seller.h
#ifndef OOP_3_SELLER_H
#define OOP_3_SELLER_H
//#include "Organization.h"
class Organization;
class Seller{
protected:
Organization*owner;
};
#endif
In the .cpp files(also called source files) you should include the headers using #include.
Your program has other problems too like many(and i mean many many)of the methods in Seller.h have no return value for methods that have non-void return type.
I tried solving some of the problems in you github code but there are just too many problems(errors and warnings) to solve. Also i would suggest you to use cpp files as well.
|
70,016,851 | 70,016,973 | Thread Sanitizer - How to interpret the Read vs Previous Write warning | I am running a program with thread sanitizers and wonder how to interpret the following warning:
==================
WARNING: ThreadSanitizer: data race (pid=2788668)
Read of size 4 at 0x7f7eefc4e298 by main thread:
[Stacktrace follows...]
Previous write of size 8 at 0x7f7eefc4e298 by thread T27:
[Stacktrace follows...]
Location is heap block of size 307272 at 0x7f7eefc1c000 allocated by thread T27
[Stacktrace follows...]
Thread T27 (tid=2790352, running) created by main thread at:
[Stacktrace follows...]
==================
I am interpreting this message as just saying that the main thread read memory written to previously by a different thread. The different thread was created by the main thread and this different thread also allocated the memory. Is this correct? If so, is there a way to suppress this particular warning in the following runs?
| The warning is a real error (unless it is a false positive).
Thread T27 wrote 8 bytes to address 0x7f7eefc4e298 and main thread read the first 4 bytes of that later without locking (as far as the sanitizer could tell). This is a race condition and undefined behaviour.
In other words, access to 0x7f7eefc4e298 is not protected by locks or other synchronization primitives. Is that the case?
If you insist, there is a way how to silence them, create a supp.txt file with:
# Silences all races originating in bar_function
race:foo_namespace::bar_function
Then run your test with TSAN_OPTIONS="suppressions=supp.txt" environment variable set. There is a sparse documentation for the format of the suppresion file. Another compile-time option using -fsanitize-ignorelist which should disable the instrumentation itself.
|
70,017,743 | 70,021,594 | Pass a template to an async function | I'm trying to run an async function passing to it a function f to execute and a template function f0 as attribute.
This is the function that I create through a template
DivideVerticesInThreads<0> f0(g, {}, {});
The template is
template <int NSegments, int Segment> struct SegmentVertices {
std::hash<Graph::vertex_descriptor> _h;
bool operator()(Graph::vertex_descriptor vd) const { return (_h(vd) % NSegments) == Segment; }
};
template <int N>
using DivideVerticesInThreads = boost::filtered_graph<Graph, boost::keep_all, SegmentVertices<4, N>>;
Then I call the async function in this way
auto handle = async(std::launch::async,f, f0);
And I pass to it the function f:
auto f = [&](G const& f0) {
for(vp = vertices(f0); vp.first != vp.second; ++vp.first){
//...
}
};
The complete piece of code is:
template<typename G>
void parallel_count_adj_luby(G g){
property_map<Graph,vertex_degree_t>::type deg = get(vertex_degree, g);
auto f = [&](G const& g1) {
for(vp = vertices(g1); vp.first != vp.second; ++vp.first){
// ...
}
};
DivideVerticesInThreads<0> f0(g, {}, {});
auto handle = async(std::launch::async,f, f0);
}
The problem is that the async function gives me this error
error: no matching function for call to 'async(std::launch, parallel_count_adj_luby(G) [with G = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::property<boost::vertex_color_t, int, boost::property<boost::vertex_degree_t, int> > >]::<lambda(const boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::property<boost::vertex_color_t, int, boost::property<boost::vertex_degree_t, int> > >&)>&, DivideVerticesInThreads<0>&)'
auto handle = async(std::launch::async,f, f0);
I don't know well c++ and future, so the error may be something dummy. What I did wrong?
| I agree somewhat with the commenters, that the problem exposition is needlessly unclear.¹
However, I think I know what's happening is due to a choice I made when presenting this sample code to you in an earlier answer.
It appears I focused on efficiency and it landed you with c++ challenges you didn't know how to handle.
I'm just going to ignore the confusion and remove the static type parameters with runtime parameters. That way your filtered graph segments can all have the same static type
Live On Compiler Explorer
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/graph/random.hpp>
#include <iostream>
#include <random>
static std::mt19937 s_prng(std::random_device{}());
using G = boost::adjacency_list<>;
using V = G::vertex_descriptor;
struct SegmentVertices {
unsigned nsegments, segment;
bool operator()(V vd) const {
return (std::hash<V>{}(vd) % nsegments) == segment;
}
};
using F = boost::filtered_graph<G, boost::keep_all, SegmentVertices>;
G make_graph() {
G g;
generate_random_graph(g, 32 * 1024 - (s_prng() % 37), 64 * 1024, s_prng);
return g;
}
void the_function(G const& g)
{
std::cout << "Full graph " << size(boost::make_iterator_range(vertices(g)))
<< " vertices\n";
}
void the_function(F const& f)
{
auto& pred = f.m_vertex_pred;
std::cout << pred.segment << "/" << pred.nsegments << " "
<< size(boost::make_iterator_range(vertices(f))) << " vertices\n";
}
int main()
{
G g = make_graph();
the_function(g);
unsigned NSegments = s_prng() % 10 + 2;
for (unsigned seg = 0; seg < NSegments; ++seg) {
the_function(F(g, {}, {seg, NSegments}));
}
}
Prints e.g.
Full graph 32736 vertices
0/3 10912 vertices
1/3 10912 vertices
2/3 10912 vertices
Or
Full graph 32741 vertices
0/7 4678 vertices
1/7 4678 vertices
2/7 4677 vertices
3/7 4677 vertices
4/7 4677 vertices
5/7 4677 vertices
6/7 4677 vertices
As you can see, using runtime filter parameters trades performance for runtime flexibility and type convenience.
¹ E.g. even the first claim "This is the function that I create through a template" makes no sense, because what follows is not a function and no template is being used to create it either.
|
70,018,040 | 70,018,361 | Template function for random number generation (static assertion failed) | I created a simple template function to generate a random number of type T (I need int or float) in range [low, high) as follows:
template <typename T>
T randm(T low, T high)
{
static std::random_device seeder;
static std::mt19937 gen(seeder());
std::uniform_real_distribution<T> dis(low, high);
return dis(gen);
}
However when I try to call it as:
int r = randm<int>(0, 10);
I get the error: "static assertion failed: result_type must be a floating point type".
I found out that if I use uniform_real_distribution<> instead of uniform_real_distribution<T>, it works, but I am not sure why (and if I am not mistaken uniform_real_distribution<> defaults to double which I don't need).
| For integral types, there is std::uniform_int_distribution. You have to apply something with if constexpr or to use SFNIAE (with type traits) to handle floating points and integrals separately. Btw. there is a note in std::uniform_real_distribution: The effect is undefined if this is not one of float, double, or long double. ("this" concerns the template type.)
Two separate functions distinguished by SFINAE:
#include <iostream>
#include <random>
template <typename T,
std::enable_if_t<std::is_integral_v<T>, int> = 0
>
T randm(T low, T high)
{
static std::random_device seeder;
static std::mt19937 gen(seeder());
std::uniform_int_distribution<T> dis(low, high);
return dis(gen);
}
template <typename T,
std::enable_if_t<std::is_floating_point_v<T>, int> = 0
>
T randm(T low, T high)
{
static std::random_device seeder;
static std::mt19937 gen(seeder());
std::uniform_real_distribution<T> dis(low, high);
return dis(gen);
}
#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__
int main()
{
DEBUG(std::cout << randm(0, 10) << std::endl);
DEBUG(std::cout << randm(0.0f, 10.0f) << std::endl);
}
Output:
std::cout << randm(0, 10) << std::endl;
4
std::cout << randm(0.0f, 10.0f) << std::endl;
9.05245
Live Demo on coliru
Using if constexpr (requires at least C++17):
#include <iostream>
#include <random>
template <typename T>
T randm(T low, T high)
{
static std::random_device seeder;
static std::mt19937 gen(seeder());
if constexpr (std::is_integral_v<T>) {
std::uniform_int_distribution<T> dis(low, high);
return dis(gen);
}
if constexpr (std::is_floating_point_v<T>) {
std::uniform_real_distribution<T> dis(low, high);
return dis(gen);
}
return T(); // ERROR?
}
#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__
int main()
{
DEBUG(std::cout << randm(0, 10) << std::endl);
DEBUG(std::cout << randm(0.0f, 10.0f) << std::endl);
}
Output:
std::cout << randm(0, 10) << std::endl;
7
std::cout << randm(0.0f, 10.0f) << std::endl;
3.51174
Live Demo on coliru
Inspired by Jarod42s comment another C++11 solution:
#include <iostream>
#include <random>
#include <type_traits>
template <typename T>
T randm(T low, T high)
{
static std::random_device seeder;
static std::mt19937 gen(seeder());
typename std::conditional<std::is_integral<T>::value,
std::uniform_int_distribution<T>,
std::uniform_real_distribution<T>
>::type dis(low, high);
return dis(gen);
}
#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__
int main()
{
DEBUG(std::cout << randm(0, 10) << std::endl);
DEBUG(std::cout << randm(0.0f, 10.0f) << std::endl);
}
Output:
std::cout << randm(0, 10) << std::endl;
2
std::cout << randm(0.0f, 10.0f) << std::endl;
4.36778
Live Demo on coliru
Jarod42 also pointed out another weakness of this approach: std::is_integral covers any integral type (including variations of char and even bool) but std::uniform_int_distribution is actually undefined if the template type is not one of short, int, long, long long, unsigned short, unsigned int, unsigned long, or unsigned long long.
A better alternative is provided in this answer to templating a random number generator in c++.
|
70,018,274 | 70,018,837 | Out of the switch scope, how can I use the template variable which is defined in switch scope in C++ | The code is as follows:
//template_test.h
enum SnType
{
Sa,
Sb,
Sc
};
//main.cc
#include <iostream>
#include "template_test.h"
using namespace std;
template<SnType _Tsn>
class Test
{
public:
void print()
{
cout << "Type is " << _Tsn << endl;
}
};
int main()
{
SnType type = Sa;
switch (type)
{
case Sa:
Test<Sa> A;
break;
case Sb:
Test<Sb> A;
break;
case Sc:
Test<Sc> A;
break;
default:
break;
}
A.print();
return 0;
}
when I run code , then the terminal shows the error: 'A' was not declared in this scope.
How can I use A out of the switch scop?
Out of the switch scope, how can I use the template variable which is defined in switch scope in C++
Thanks a lot!
|
How can I use A out of the switch scope?
You can't. It has ceased to exist.
Aside: All names that start with and underscore and are followed by a capital letter are reserved, _Tsn makes your program is ill-formed.
You'll have to do your type-dependant things within the switch, e.g.
#include <iostream>
enum SnType
{
Sa,
Sb,
Sc
};
template<SnType Tsn>
class Test
{
public:
void print()
{
std::cout << "Type is " << Tsn << std::endl;
}
};
template<SnType Tsn>
void testPrint()
{
Test<Tsn>{}.print();
}
int main()
{
SnType type = Sa;
switch (type)
{
case Sa:
testPrint<Sa>();
break;
case Sb:
testPrint<Sb>();
break;
case Sc:
testPrint<Sc>();
break;
default:
break;
}
return 0;
}
|
70,018,502 | 70,019,572 | Compiler can't execute constexpr expression | I have code something like this:
template<typename ... Args>
constexpr size_t get_init_size(Args ... args) {
return sizeof...(Args);
}
template<typename ... Args>
constexpr auto make_generic_header(Args ... args) {
constexpr size_t header_lenght = get_init_size(args...);
return header_lenght;
}
constexpr auto create_ipv4_header() {
constexpr auto x = make_generic_header(0b01, 0b10, 0b01);
return x;
}
I know it is dummy code, but I isolate it to find error.
Compiler give me error(GCC):
In instantiation of 'constexpr auto make_generic_header(Args&& ...) [with Args = {int, int, int}]':
/tmp/tmp.CaO5YHcqd8/network.h:39:43: required from here
/tmp/tmp.CaO5YHcqd8/network.h:31:22: error: 'args#0' is not a constant expression
31 | constexpr size_t header_lenght = get_init_size(args...);
| ^~~~~~~~~~~~~
I tried add qualifier const to function parameters but it same doesn't work. In theory all this function can calculate in compile time. But where is problem I can't find with my knowledge.
| I rewrite the code that will be work and I think will be execute in compile time:
template<typename ... Args>
constexpr auto make_generic_header(const Args ... args) {
std::integral_constant<size_t, sizeof...(Args)> header_lenght;
return header_lenght.value;
}
constexpr auto create_ipv4_header() {
constexpr auto x = make_generic_header(0b01, 0b10, 0b01);
return x;
}
I removed function get_init_size and used code part of template parameter(It is guaranteed that it is will be execute on compile time) and after return the number of arguments passed to function(For std::integral_constant for all object value same and know on compile time)
|
70,019,717 | 70,019,904 | Replace const std::string passed by reference, with std::string_view | I've got the following method which gets std::string as input argument.
int func(const std::string &filename);
From it's signature, the input type refers passed by reference (no copy is made) and shouldn't be changed (by the const prefix).
Would it be equivalent of using std::string_view instead, which is also used for read only ?
int func(std::string_view filename);
And if not, so in which aspect they're not similar (runtime, memory consumption, functionality, etc.)
| No it's not equivalent.
There are two cases where using std::string const& is a better alternative.
You're calling a C function that expects null terminated strings. std::string_view has a data() function, but it might not be null terminated. In that case, receiving a std::string const& is a good idea.
You need to save the string somewhere or you're calling a C++ function that expects a std::string const&. Sometimes they are function from libraries that would be undesirable to change.
All other cases would be better with std::string_view
There is also some key differences between a string view and a reference to a string.
First, you are passing by reference, not by value. The compiler has to reference it everytime it want to access the capacity, size or data.
Second, a string view don't use capacity, only a size and a data. It also means that loads can be omitted since you are passing it by value, as a local variable with limited scope.
|
70,020,184 | 70,020,684 | how to detect words in an image with OpenCV and Tesseract properly | I'm working on an application which reads an image file with OpenCV and processes the words on it with Tesseract.
With the following code Tesseract detects extra rectangles which don't contain text.
void Application::Application::OpenAndProcessImageFile(void)
{
OPENFILENAMEA ofn;
ZeroMemory(&ofn, sizeof(OPENFILENAMEA));
char szFile[260] = { 0 };
// Initialize remaining fields of OPENFILENAMEA structure
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = mWindow->getHandle();
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "JPG\0*.JPG\0PNG\0*.PNG\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
//open the picture dialog and select the image
if (GetOpenFileNameA(&ofn) == TRUE) {
std::string filePath = ofn.lpstrFile;
//load image
mImage = cv::imread(filePath.c_str());
//process image
tesseract::TessBaseAPI ocr = tesseract::TessBaseAPI();
ocr.Init(NULL, "eng");
ocr.SetImage(mImage.data, mImage.cols, mImage.rows, 3, mImage.step);
Boxa* bounds = ocr.GetWords(NULL);
for (int i = 0; i < bounds->n; ++i) {
Box* b = bounds->box[i];
cv::rectangle(mImage, { b->x,b->y,b->w,b->h }, { 0, 255, 0 }, 2);
}
ocr.End();
//show image
cv::destroyAllWindows();
cv::imshow("İşlenmiş Resim", mImage);
}
}
And here is the output image
As you can see Tesseract processes areas which don't contain words at all.
How can I fix this?
| Tesseract is based on character recognition more than text detection. Even there is no text in some areas tesseract can see some features as a text.
What you need to do is that using a text detection algorithm to detect text areas first and then apply tesseract. Here is a tutorial for a dnn model for text detection which is really good.
I quickly applied your image to this and here is the output:
You can get more better results by changing the input parameters of the model. I just used the default ones.
|
70,020,343 | 70,020,510 | Alternative to template ADL for GCC <= 10 | Consider the following valid C++20 code:
#include <utility>
namespace foo
{
template<typename... Args>
struct tuple : Args... { };
template<std::size_t N, typename... Args>
auto get(tuple<Args...>) { return 0; }
}
namespace bar
{
template<typename... Args>
struct tuple : Args... { };
template<std::size_t N, typename... Args>
auto get(tuple<Args...>) { return 0; }
}
template<class Tuple, std::size_t... N>
auto for_each(Tuple& args, std::index_sequence<N...>) {
(get<N>(args), ...);
}
int main()
{
struct test { };
foo::tuple<test> t;
for_each(t, std::make_index_sequence<1>());
}
Here, get<N> is able to be resolved through ADL thanks to a C++20 addition (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0846r0.html)
My question is, what are the workarounds to this before C++20, which do not require the method for_each to know about the foo and bar namespaces ?
I'd be happy with anything that works starting from GCC 8.
| You can add a dummy function and leave it without definition to make the compiler happy.
When the template is instatiated the right methods will be found through ADL.
#include <utility>
#include <tuple>
namespace foo
{
template<typename... Args>
struct tuple : Args... { };
template<std::size_t N, typename... Args>
auto get(tuple<Args...>) { return 0; }
}
namespace bar
{
template<typename... Args>
struct tuple : Args... { };
template<std::size_t N, typename... Args>
auto get(tuple<Args...>) { return 0; }
}
template <typename... T>
struct Dummy;
template <std::size_t N, typename... Args>
auto get(Dummy<Args...>);
template<class Tuple, std::size_t... N>
auto for_each(Tuple& args, std::index_sequence<N...>) {
(get<N>(args), ...);
}
int main()
{
struct test { };
foo::tuple<test> t;
for_each(t, std::make_index_sequence<1>());
}
Edit
As suggested by @Jarod42 we can do
template <std::size_t N>
void get() = delete;
The compiler can't rule out that there is a valid specialization for that template later on, so the fact that it's deleted doesn't really matter here.
|
70,020,593 | 70,021,054 | std::make_from_tuple doesn't compile without constructor | I have a simple struct:
struct A
{
int a;
int b;
int c;
// A(int a, int b, int c) : a{a}, b{b}, c{c} { }
};
The constructor is commented for now. I am trying to create object of type A in a such way:
auto t = std::make_tuple(1, 2, 3);
A a = std::make_from_tuple<A>(std::move(t));
but it doesn't compile. MSVC gives a message:
<function-style-cast>: cannot convert from initializer_list to _Ty.
After I uncomment the constructor of struct A, it starts working.
The question is: why std::make_from_tuple() requires a user-defined constructor instead of default one?
| If you look closely at the implementation of make_from_tuple in the standard:
namespace std {
template<class T, class Tuple, size_t... I>
requires is_constructible_v<T, decltype(get<I>(declval<Tuple>()))...>
constexpr T make-from-tuple-impl(Tuple&& t, index_sequence<I...>) {
return T(get<I>(std::forward<Tuple>(t))...);
}
}
It uses parentheses (()) to initialize T with direct initialization. Since A is an aggregate, it cannot use parentheses for initialization in C++17, and can only use curly braces ({}) for list initialization.
It is worth noting that P0960 makes it possible to use parentheses to initialize aggregates in C++20, so your code is well-formed in C++20.
|
70,020,637 | 70,020,818 | The pointer changes the value of the address it points to | I would expect pFirst to always point to the same place in the address. However it looks like pFirst moves along with pCurrent even though the function only entered the Else statement once.
Note:code is creating a linked list .
void Push(T data) {
++_size;
Data d = Data(data);
if (_pCurrent != nullptr) _pCurrent->SetNext(&d);
else _pFirst = &d;
_pCurrent = &d;
}
| d is created locally, so it does not exist after the function is over. Debug error is a little bit strange, because the program initializes a new element at the same address, so I did not immediately understand exactly what is happening.
This is the working version:
void Push(const T data) {
Data*d = new Data(data);
++_size;
if (_pCurrent != nullptr)
_pCurrent->_pNext = d;
else
_pFirst = d;
_pCurrent = d;
}
|
70,020,760 | 70,020,797 | How to make a class variable in one line? | In C++ how make a class variable in one line?
For example:
I have a class:
class point{
public:
int x;
int y;
};
How to make a variable in one line like java you can do new point(x, y), currently I do make a tmp and then push back to vector or something, are the simply way like java can do what I do in one line?
| For creating a variable of type point on the stack you can use:
point myVariable{5,6};//this creates a point type variable on stack with x=5 and y=6;
So the complete program would look like:
#include <iostream>
class point{
public:
int x;
int y;
};
int main()
{
point myVariable{5,6};
return 0;
}
The output of the above program can be seen here.
If you want to create a vector of point objects and then add objects into it, then you can use:
//create point objects
point p1{5,6};
point p2{7,8};
//create a vector
std::vector<point> myVector;
//add p1 and p2 into the vector
myVector.push_back(p1);
myVector.push_back(p2);
|
70,020,887 | 70,054,848 | How cmake judging target_link_libraries item is a library name or a target? | I have some troubles in cmake target_link_libraries function.
In my case,there are three projects like this,which means A depends on B,B depends on C
A(exec) --> B(static library) --> C(static library alias C::C)
I write a CMakeLists.txt for B like this:
find_package(C REUQIRED)
add_library(B ...)
target_link_libraries(B PRIVATE C::C)
And it works well ,complie successfully.
A's cmake file like this:
find_package(B REQUIRED)
add_exectuable(A ...)
target_link_libraries(A B)
It reports error when linking A,cmake set a linker flags "-lC::C",and then ld said C::C not exist.
How it happend?I think C::C is a target and A should know it,but cmake think it is a library name.And I think A should not know B depends on C,it's a private library.
I don't want to write find_packge(C) in A's cmake,because C is a static library,I think B should handle all dependcies of C,that's right?
So anyone knows how to fix it ?
| I solved this problem finally.
In my case,B using C's funtion in template code,and B does not instantiate this template,so C::C would not link into B's static library.But A would instantiate B's template,so A need C::C,that's why B's PRIVATE flag was useless.
In order to help A found the C::C,I should use find_depecncy(C) in B's config.cmake to let A knows B's depency when use find_package(B).
|
70,021,319 | 70,397,628 | How do I know when X server has completed the drawing? | Suppose I want to draw rectangles one after another. How do I know when X server has completed drawing one rectangle? Is there a way to get any confirmation from X server?
In the following code I draw the first rectangle at 500,500 and redraw the same rectangle in the expose handler. After that I draw a new rectangle at 1000,1000. The problem is that first rectangle was never drawn. How many times do I've to go through the Expose event handler? HOW MANY TIMES IS ENOUGH?
#include <X11/Xlib.h>
#include <X11/extensions/XTest.h>
#include <X11/Xutil.h>
#include <iostream>
using namespace std;
int main(){
Display *disp;
int screen;
Window win;
GC gc;
disp = XOpenDisplay(NULL);
screen = DefaultScreen(disp);
XColor color;
Colormap colormap;
char black[] = "#ffffff";
colormap = DefaultColormap(disp, 0);
XParseColor(disp, colormap, black, &color);
XAllocColor(disp, colormap, &color);
win = XCreateSimpleWindow(disp, RootWindow(disp, screen), 10,
10, 1500, 1500, 0, WhitePixel(disp, screen), color.pixel);
XSizeHints my_hints = {0};
my_hints.flags = PPosition | PSize;
my_hints.x = 10;
my_hints.y = 10;
my_hints.width = 1500;
my_hints.height = 1500;
XSetNormalHints(disp, win, &my_hints);
XMapWindow(disp, win);
gc = XCreateGC(disp, win, 0, 0);
XColor color1;
Colormap colormap1;
char red[] = "#000000";
colormap1 = DefaultColormap(disp, 0);
XParseColor(disp, colormap1, red, &color1);
XAllocColor(disp, colormap1, &color1);
XSetForeground(disp, gc, color1.pixel);
XSelectInput(disp, win, ExposureMask);
int x1 = 500;
int x2 = 500;
XEvent event;
int i = 0;
while(true){
XDrawRectangle(disp, win, gc, x1, x1, 500, 500);
XNextEvent(disp, &event);
if(event.xany.window == win){
if(event.type == Expose){
cout << i << endl;
XDrawRectangle(disp, win, gc, x1, x2, 500, 500);
}
}
i++;
x1 += 500;
x2 += 500;
}
XFreeGC(disp, gc);
XDestroyWindow(disp, win);
XCloseDisplay(disp);
return 0;
}
Output
0
1
2
3
| It seems you are expecting XDrawRectangle() to generate Expose events, but it will never happen, because this is not how it works. Expose events are generated when a window is mapped, resized, moved or when an obscuring window is unmapped, but not when drawing into a window. Actually, the only Expose event you are interesting in is the one generated by XMapWindow(). After receiving this first Expose event you know that window is mapped and can be drawn to. You should also call XClearWindow() before mapping a window to ensure it doesn't contain any garbage. Sometimes you may also want to check if (event.xexpose.count == 0) to process only the latest event in the queue, but it shouldn't be necessary in your example. Then just draw into the window and probably flush the buffer with XFlush() or XSync() after every draw. This should do what you want(I modified coordinates a little bit, but the principle is the same):
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/XTest.h>
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
int main()
{
Display* disp;
int screen;
Window win;
GC gc;
disp = XOpenDisplay(NULL);
screen = DefaultScreen(disp);
XColor color;
Colormap colormap;
char black[] = "#ffffff";
colormap = DefaultColormap(disp, 0);
XParseColor(disp, colormap, black, &color);
XAllocColor(disp, colormap, &color);
win = XCreateSimpleWindow(disp,
RootWindow(disp, screen),
10,
10,
1500,
1500,
0,
WhitePixel(disp, screen),
color.pixel);
XSizeHints my_hints = {0};
my_hints.flags = PPosition | PSize;
my_hints.x = 10;
my_hints.y = 10;
my_hints.width = 1500;
my_hints.height = 1500;
XSetNormalHints(disp, win, &my_hints);
gc = XCreateGC(disp, win, 0, 0);
XColor color1;
Colormap colormap1;
char red[] = "#000000";
colormap1 = DefaultColormap(disp, 0);
XParseColor(disp, colormap1, red, &color1);
XAllocColor(disp, colormap1, &color1);
XSetForeground(disp, gc, color1.pixel);
XSelectInput(disp, win, ExposureMask);
int x = 10;
int y = 10;
int i = 0;
XClearWindow(disp, win); // Clear window from possible garbage
XMapWindow(disp, win);
XEvent event;
while (true)
{
// Wait for window to be mapped
XNextEvent(disp, &event);
if (event.xany.window == win && event.type == Expose)
{
break;
}
}
for (int k = 0; k < 20; ++k)
{
std::cout << i << '\n';
XDrawRectangle(disp, win, gc, x, y, 500, 500);
XFlush(disp);
++i;
x += 10;
y += 10;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
XFreeGC(disp, gc);
XDestroyWindow(disp, win);
XCloseDisplay(disp);
return 0;
}
|
70,022,433 | 70,022,800 | How to solve the Visual Studio problem at the execution of a program | I need to solve an error that says "Please Select a Valid Startup Item" when i try to execute a program in Visual Studio. I am working with C++.
| Dou you have the c++ compiler pluing for VS? you can install it from the extensions panel in VS
The file is in a project? try putting it in one.
Are you sure you have a method int main(){reutrn 0;}?
Maybe whit more info i can help you more :)
|
70,022,460 | 70,825,558 | Do libraries compiled with MinGW work with MSVC? | Problem:
I would use a MinGW library in Visual Studio project.
How my system is built:
I downloaded ZBar library for my Windows 10 system ( zbar-0.23.91-win_x86_64-DShow.zip
This is the link: https://linuxtv.org/downloads/zbar/binaries/).
I have these files in the folder of lib and bin:
libzbar.a
libzbar.dll.a
libzbar.la
libzbar-0.dll
Error when build:
error LNK2019: unresolved external symbol __mingw_vsnprintf referenced in snprintf
My question
Do libraries compiled with MinGW work with MSVC?
| No, libraries compiled on MinGW can't be used with MSVC. The main reasons are:
Lack of ABI compatibility. That is to say that in binary, the way things can be laid out are different depending on the compiler.
Difference in how the standard library is implemented. The standard library can be implemented in many ways. The C++ Standard just says how functions should behave and does not force compiler developers to implement them in the same way.
In general, things compiled with one compiler aren't compatible with another compiler.
|
70,022,701 | 70,043,893 | Basler's Pylon SDK, on memory Image saving | I am working on a Pylon Application where performance is crucial , saving images directly to the disk might throttle the performance, so I want to allocate a memory buffer where I can store an array of Pylon Images, and save them to disk later, what is the best approach I could take?
| I have managed to solve it by making an array of type (Pylon::CPylonImage) and save the captured images on it using a converter (Pylon::CImageFormatConverter) like the following code block
Pylon::CImageFormatConverter::Convert(Pylon::CPylonImage[i],Pylon::CGrabResultPtr)
|
70,022,947 | 70,072,828 | TouchGFX gui automated testing | Checking for feasibility of automated UI testing for TouchGFX. Is there a library that helps in identifying the application window handle and use it to choose UI elements and drive the operations in each window?
| I work as part of the TouchGFX team on a daily basis.
We have a test-framework, only for internal use currently, that we plan to share with the public at some point. It uses the CubeProgrammer API to, through UnitTest++, step an application x number of times, dump the frame-buffer and do comparisons against golden images, check render times, and lots more. We use it for both framework unit tests, TouchGFX Generator tests and to test the board packages available through TouchGFX Designer.
What prevents you from performing this kind of test, currently, is that you need a HAL that isn't free-running and can take instructions from a PC source (Executing test-suites through UnitTest++, sending commands over CubeProgrammer API).
I hope we'll be able to share it soon.
|
70,023,071 | 70,023,348 | C++ cannot call set_value for promise move-captured in a lambda? | I'm trying to write a fairly simple method that returns a future. A lambda sets the future. This is a minimal example. In reality the lambda might be invoked in a different thread, etc.
#include <future>
std::future<std::error_code> do_something() {
std::promise<std::error_code> p;
auto fut = p.get_future();
auto lambda = [p = std::move(p)] {
std::error_code error;
p.set_value(error);
};
lambda();
return std::move(fut);
}
int main() { return do_something().get().value(); }
For some reason I get a type error. VSCode intellisense says:
no instance of overloaded function "std::promise<_Ty>::set_value [with _Ty=std::error_code]" matches the argument list and object (the object has type qualifiers that prevent a match) -- argument types are: (std::remove_reference_t<std::error_code &>) -- object type is: const std::remove_reference_t<std::promise<std::error_code> &>
And MSVC compiler says:
error C2663: 'std::promise<std::error_code>::set_value': 2 overloads have no legal conversion for 'this' pointer
I really don't understand the VS Code error. Is it saying that it thinks error is a const promise<error_code>? How do I correctly call set_value on a promise which was moved inside a lambda's capture?
| By default lambda stores all its captured values (non-references) as const values, you can't modify them. But lambda supports keyword mutable, you can add it like this:
[/*...*/](/*...*/) mutable { /*...*/ }
This will allow inside body of a lambda to modify all its values.
If for some reason you can't use mutable, then you can use other work-around:
[/*...*/, p = std::make_shared<ClassName>(std::move(p)), /* ... */](/*...*/) {/*...*/}
In other words wrap your moved value into std::shared_ptr, you can also use std::unique_ptr if you like.
Wrapping into shared pointer solves the problem, because shared pointer (unique also) allows to modify its underlying object value even if pointer itself is const.
Don't forget inside the body of a lambda to dereference p as a pointer, in other words if you used p.SomeMethod(), now you have to use p->SomeMethod() (with -> operator).
|
70,023,172 | 70,023,318 | When does "requires" cause a compiler error | Consider this code:
struct Bad {};
int main() {
static_assert(requires(int n, Bad bad) { n += bad; });
}
Compiling with Clang 13 and -std=c++20, I get the following error:
<source>:5:48: error: invalid operands to binary expression ('int' and 'Bad')
static_assert(requires(int n, Bad bad) { n += bad; });
~ ^ ~~~
1 error generated.
But I would have expected the requires expression to return false and fail the static_assert.
If I rewrite this concept as a template constraint, I get the conditional compilation that I expect i.e. the compiler doesn't complain that there is no operator+= and the requires returns false.
| A notation from the standard:
If a requires-expression contains invalid types or expressions in its requirements, and it does not appear within the declaration of a templated entity, then the program is ill-formed.
So requires only gains this capability when it is in a template.
|
70,023,236 | 70,023,337 | delete a double pointer | How to properly delete a double-pointer array? when I tried this code, memcheck told me that "Use of the uninitialized value of size 8" and "Invalid write of size 4". I couldn't figure out where I did wrong.
struct Node
{
int value;
Node* next;
};
int main()
{
Node** doublePtrNode= new Node* [10];
for (unsigned int i = 0; i < 10; i++)
{
doublePtrNode[i]->value=i;
}
for (unsigned int i = 0; i < 10; i++)
{
delete doublePtrNode[i];
}
delete[] doublePtrNode;
return 0;
}
| You are already deallocating what you have allocated but doublePtrNode[i]->value=i; assumes that you've allocated a Node there, but you haven't so the program has undefined behavior.
If you are going to use raw owning pointers, you could fix it like this:
Node** doublePtrNode = new Node*[10];
// now allocate the actual `Node`s too:
for(unsigned i = 0; i < 10; ++i) doublePtrNode[i] = new Node;
// your current assigning loop goes here
// deallocate the `Node`s:
for(unsigned i = 0; i < 10; ++i) delete doublePtrNode[i];
delete[] doublePtrNode;
A much simpler and safer option is to use a std::vector<Node>. That way you do not need any manual memory management. It does it for you.
#include <vector>
int main() {
std::vector<Node> nodes(10);
// your current assigning loop goes here
} // all `Node`s are deleted when `nodes` goes out of scope
|
70,023,321 | 70,024,660 | get value of postfix experssion from number more than one digit | #include <iostream>
#include <string>
#include <stack>
using namespace std;
float postix_evalute(string expr)
{
stack<float> stk;
for (int x = 0; x < expr.length(); x++)
{
if (isdigit(expr[x]))
{
stk.push((expr[x] - '0'));
}
else
{
float val;
float op2 = stk.top();
stk.pop();
float op1 = stk.top();
stk.top();
switch (expr[x])
{
case '+':
val = op1 + op2;
break;
case '-':
val = op1 - op2;
break;
case '*':
val = op1 * op2;
break;
case '/':
val = op1 / op2;
break;
}
stk.push(val);
}
}
return stk.top();
}
int main()
{
string line;
cout << "The Value Of expression" << endl;
cin >> line;
cout << postix_evalute(line) << endl;
return 0;
}
When I enter the expression "213+" I get the output "4"; but I expect to get 24 (21+3).
What should I do to take operands with more than on digit?
| You need a way to differentiate the tokens of your postfix expressions. For example, if the input is 213+, a parser would typically read that as 213 and +. For these simple expressions, you could separate the different tokens with whitespaces, as in 21 3 +. Then, having that input in a string, you could read each token with an input string stream.
float postix_evalute(std::string input)
{
std::stack<float> stk;
std::istringstream iss{input};
std::string token{};
while (not iss.eof())
{
iss >> token;
try
{
stk.push(std::stof(token));
}
catch (const std::invalid_argument& ex)
{
assert(stk.size() >= 2);
float op2 = stk.top(); stk.pop();
float op1 = stk.top(); stk.pop();
float val{};
if (token == "+") { val = op1 + op2; }
else if (token == "-") { val = op1 - op2; }
else if (token == "*") { val = op1 * op2; }
else if (token == "/") { val = op1 / op2; }
else { throw std::runtime_error{std::string{"unknown token: " + token}}; }
stk.push(val);
}
}
return stk.top();
}
Demo 1: using 21 3 + as an input.
Demo 2: using 21 3 # as an input.
|
70,023,711 | 70,025,365 | Upper-triangle matrix looping | If I have the following matrix for example:
enter image description here
The values in the tables are an index of the elements.
for (int count =0; index<9; count++) {
//row = function of index
//column = function of index
}
In other words, how can I get the row and column from the index of an upper triangle of a matrix if it was ordered as in the photo.
I've been thinking about this for a while but I can't seem to figure it out!
| row_index(i, M):
ii = M(M+1)/2-1-i
K = floor((sqrt(8ii+1)-1)/2)
return M-1-K
column_index(i, M):
ii = M(M+1)/2-1-i
K = floor((sqrt(8ii+1)-1)/2)
jj = ii - K(K+1)/2
return M-1-jj
where M is the size of the matrix
Here's a link algorithm for index numbers of triangular matrix coefficients
which gives more details about the answer algebraically. credit to https://stackoverflow.com/users/4958/shreevatsar
Along with the comment from https://stackoverflow.com/users/2019794/michael-bauer
|
70,023,790 | 70,023,874 | Control flow with iterators | Say I have something like this:
void myFunk(std::vector<T>& v, std::vector<T>::iterator first, std::vector<T>::iterator last) {
while (first != last) {
if ((*first) > (*last)) {
T someT;
v.push_back(someT);
}
first++;
}
}
int main(){
std::vector<T> foo = {some, T, values};
myFunky(foo, foo.begin(), foo.end())
return 0;
}
Would this lead to an infinite loop, or would it end after foo.size() iterations? In other words, would the last iterator be updated as foo grew, or would it retain the value given in the function call?
I'm assuming last would change, since it's a pointer to a position, but would like some confirmation.
|
Would this lead to an infinite loop, or would it end after foo.size() iterations?
Neither. What you are doing is undefined behavior, for a couple of reasons:
You are modifying the vector while iterating through it.
If the vector reallocates its internal storage when pushing a new item, all existing iterators into the vector are invalidated, including both iterators you are using to loop with. But even just pushing a new item always invalidates the end() iterator, at least.
See Iterator invalidation rules for C++ containers
You are dereferencing the end() iterator, which never refers to a valid element.
I'm assuming last would change, since it's a pointer to a position
It can't change, since you passed it into the myFunc function by value, so it is a copy of the original end() iterator. If end() changes value, last will not change value, since it is a copy.
In any case, iterators are not necessarily implemented as pointers, but pointers are valid iterators. But it doesn't matter in this case. Even if vector::iterator were just a simple pointer, last would still get invalidated upon every push/reallocation.
|
70,023,798 | 70,027,578 | Armadillo Sparse Matrix Size in Bytes | I would like to assess how large Armadillo sparse matrices are. The question is related to this answer regarding dense matrices.
Consider the following example:
void some_function(unsigned int matrix_size) {
arma::sp_mat x(matrix_size, matrix_size);
// Steps entering some non-zero values
std::cout << sizeof(x) << std::endl;
}
Unfortunately, sizeof does, as in the dense matrix case, not return the size of the matrix itself, but rather the size of a pointer or some other small object. The size of the sparse matrix should not simply be the number of non-zero elements times the data type's size. Armadillo stores sparse matrices in a compressed format. And on top of the cell values, there should also be a matrix or vectors storing the cell indices. And I guess that the matrix also has a header storing information about the object.
| There are three key properties:
n_rows
n_cols and
n_nonzero
The last value represents the number of cells 0 <= n_nonzero <= (n_rows*n_cols) which have a value.
You can use this to know the density (which is also displayed as a percentage with .print, e.g.
[matrix size: 3x3; n_nonzero: 4; density: 44.44%]
(1, 0) 0.2505
(0, 1) 0.9467
(0, 2) 0.2513
(2, 2) 0.5206
I used these properties to implement sp_matrix serialization before: How to serialize sparse matrix in Armadillo and use with mpi implementation of boost?
The actual number of bytes allocated will be roughly correlating to n_nonzero, but you have to account for /some/ overhead. In practice the best way to measure actual allocations is by using instrumented allocators, or (the logical extension of that idea) memory profilers. See e.g. How to find the memory occupied by a boost::dynamic_bitset?
|
70,023,880 | 70,024,290 | How to return an array in method decleration using C++? | I am trying to write C++ code suitable for object oriented programming.
I have two classes, namely, Student and Course. In the Student class, I have quiz_scores which is a 1-D array of 4 integers. I need both set and get methods, both are used in natural common way.
In the following, I implement setQuizScores method:
void Student :: setQuizScores(int* quizscores){
for(int i = 0; i<4; i++){
quiz_scores[i] = quizscores[i];
}
Where quizscores are my private members.
Now, next thing is that I want to return this quiz_scores array in the getQuizScores for each students of Student class.
However, the problem is that C++ does not allow us to return arrays directly. Instead, I want the structure of my code as following:
int Student :: getQuizScores(){
Do something;
return the elements of quiz_scores;
}
How can I do that efficiently?
I prefer not to use the Standard Template Library (STL), so I need to create my own arrays and access them according to the explanation above.
| Just as setQuizScores() is able to take a pointer to an array, so too can getQuizScores() return a pointer to the quiz_scores member array, eg:
const int* Student::getQuizScores() const {
// do something...
return quiz_scores;
}
The caller can then access the array elements as needed, eg:
Student s;
...
const int *scores = s.getQuizScores();
for(int i = 0; i < 4; ++i){
cout << scores[i] << ' ';
}
Alternatively, since the array is fixed size, you can return a reference to the array instead, eg:
typedef int scoresArr[4];
scoresArr quiz_scores;
...
const scoresArr& Student::getQuizScores() const {
// do something...
return quiz_scores;
}
Student s;
...
const scoresArr &scores = s.getQuizScores();
for(int i = 0; i < 4; ++i){
cout << scores[i] << ' ';
}
|
70,024,312 | 70,024,460 | Using accumulate method but can't the first element is always shown as 0 | I am trying to write a programm which returns a list whose n-th element is the sum of the first n Values of the transferred list.
list<int> summe(list<int> liste) {
list<int> neueListe;
list<int>::iterator itr;
itr = liste.begin();
int sum = 0;
int n = 0;
cout << "Liste mit Summen: " << endl;
cout << "{ " << endl;
for (itr = liste.begin(); itr != liste.end(); itr++) {
sum = accumulate(liste.begin(), itr, 0);
neueListe.push_back(sum);
cout << sum << endl;
n++;
}
cout << " }";
return neueListe;
}
int main() {
//Aufgabe 2.2 Teil 2
list<int> l = { 1,2,3,4,5 };
Algo a;
a.summe(l);
}
The output is: 0,1,3,6,10
I think the problem is, that the first loop is accumulate(liste.begin(), liste.begin(), 0); which should be always 0. However I have no idea how to get the first element (although its just one element so theres no need to accumulate).
I want the following output: 1,3,6,10,15.
| You are using a wrong algorithm. For this task there already exists the appropriate algorithm std::partial_sum declared in the header <numeric>.
Here is a demonstration program.
#include <iostream>
#include <list>
#include <iterator>
#include <numeric>
std::list<int> summe( const std::list<int> &liste )
{
std::list<int> neueListe;
std::partial_sum( std::begin( liste ), std::end( liste ),
std::back_inserter( neueListe ) );
return neueListe;
}
int main()
{
std::list<int> l = { 1, 2, 3, 4, 5 };
auto l2 = summe( l );
for ( const auto &item : l2 )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
1 3 6 10 15
Or you can transfer the implementation of the algorithm inside your function. For this purpose it is enough to have one loop.
|
70,024,327 | 70,024,368 | C++ Strange Results of String Range Constructor | I have some code similar to this:
std::istringstream iss{"SomeChars"};
// Some read ops here (though the problem stays even without them)
std::string reconst(iss.str().cbegin(), iss.str().cbegin() + iss.tellg());
std::cout << reconst << std::endl;
The result is always some garbled string. Here is a program demonstrating this.
The program works when I store iss.str() in a std::string_view or std::string. However, I still have my question:
Questions:
Why does the program behave this way?
I can't see how it would be interpreted this way, but is this the most vexing parse?
| The str function returns the string by value. That means each call to str gives you a new string object, and your iterators are pointing to those temporary strings, not the string that is the buffer for the stringstream. This cant work, because the iterators need to point into the same object, not different objects that have the same value.
|
70,024,770 | 70,024,967 | Why is my loop not restarting to the first iteration? C++ | I'm making a Dice Game in C++. I was wondering why it doesn't restart the loop. The game is Best of 3. It's supposed to restart the loop as long as the player wants to keep playing. However it only restarts the loop once. The second time I press 'Y' or yes in this case it just exits the program.
I've tried putting the restart in a nested while loop but it doesn't seem to work either.
restart:
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;
cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;
if (cDice1 > pDice1) {
cout << "Computer wins!" << endl << endl;
cWin++;
} if (pDice1 > cDice1) {
cout << "Player wins!" << endl << endl;
pWin++;
} if (pDice1 == cDice1) {
cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
cout << "Player wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}if (cWin > pWin) {
cout << "Computer wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}
}
| First, is this all your code? I noticed most of your variables seem to be declared outside of the provided code block. If so, is your "Y" being declared as a char and not a string type to match your condition type?
It looks like you are failing to set your pWin and cWin back to zero when it returns to the top. You can fix with:
restart:
cWin = 0;
pWin = 0;
while ((pWin != 2) && (cWin != 2))
{
pDice1 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;
cout << "Player score is: " << pDice1 << endl;
cout << "Computer score is: " << cDice1 << endl;
if (cDice1 > pDice1) {
cout << "Computer wins!" << endl << endl;
cWin++;
} if (pDice1 > cDice1) {
cout << "Player wins!" << endl << endl;
pWin++;
} if (pDice1 == cDice1) {
cout << "It's a draw!" << endl << endl;
} if (pWin > cWin) {
cout << "Player wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}if (cWin > pWin) {
cout << "Computer wins this round! Do you wish to keep playing?" << endl;
cin >> Y;
if (Y == 'y') {
goto restart;
}
else {
exit(0);
}
}
}
|
70,024,894 | 70,027,936 | How to make my program ask for administrator privileges on execution | I have searched and wondered how certain programs ask you to let them have administrator permissions when you start them up normally but haven't really found any good answer, I suppose they use something in Windows API but I haven't found anything that would help me.
| Add a manifest file into your EXE as described here:
http://msdn.microsoft.com/en-us/library/bb756929.aspx
|
70,025,215 | 70,026,402 | How is the lvalue problem solved for SIMD inline asm with memory output operands in a 2D array? | I am trying to write a function that will fill my float matrix with zeros using ymm registers.
After not a long time I wrote this function:
void fillMatrixByZeros(float matrix[N][N]){
for (int k = 0; k < N; k += 8){
for (int i = 0; i < N; ++i){
asm volatile (
"vxorps %%ymm0, %%ymm0, %%ymm0;"
"vmovups %%ymm0, (%0)"
: "=m"(matrix[i] + k)
:
: "%ymm0", "memory"
);
}
}
}
I tried to compile my whole code and I got this error:
prog.cpp: In function ‘void fillMatrixByZeros(float (*)[16])’:
prog.cpp:35:8: error: lvalue required in asm statement
35 | );
| ^
prog.cpp:35:8: error: invalid lvalue in asm output 0
I made a conclusion that matrix[i]+k is a rvalue or something like, so it can't be used there.
After googling, I came up with two solutions:
First:
void fillMatrixByZeros(float matrix[N][N]){
for (int k = 0; k < N; k += 8){
for (int i = 0; i < N; ++i){
asm volatile (
"vxorps %%ymm0, %%ymm0, %%ymm0;"
"vmovups %%ymm0, (%0)"
:
: "r"(matrix[i] + k)
: "%ymm0", "memory"
);
}
}
}
Second:
void fillMatrixByZeros(float matrix[N][N]){
long long int matrixPointer;
for (int k = 0; k < N; k += 8){
for (int i = 0; i < N; ++i){
asm volatile (
"vxorps %%ymm0, %%ymm0, %%ymm0;"
"vmovups %%ymm0, (%0)"
: "=r"(matrixPointer)
: "0"(matrix[i] + k)
: "%ymm0", "memory"
);
}
}
}
These functions work correctly. And I want to know why.
Why there are no any lvalue problems in first function? And what is going on in the second function?
| You cannot assign to matrix[i] + k, so it is not an lvalue. The m constraint expects an object in memory, not its address. So to fix this, supply the object you want to assign to instead of its address:
void fillMatrixByZeros(float matrix[N][N]){
for (int k = 0; k < N; k += 8){
for (int i = 0; i < N; ++i){
asm volatile (
"vxorps %%ymm0, %%ymm0, %%ymm0;"
"vmovups %%ymm0, %0"
: "=m"(matrix[i][k])
:
: "%ymm0", "memory"
);
}
}
}
This is the correct way to access objects in memory in an inline assembly statement.
The solutions using an r constraint with the address for the operand and then doing an explicit dereference work, too. But they are likely less efficient because they prevent the compiler from using some other addressing mode, like a SIB addressing mode. Instead it has to first materialise the address in a register.
Your last example is a bit silly. It uses coupled asm operands to essentially perform matrixPointer = matrix[i] + k before passing that to the inline assembly statement. This is a pretty roundabout way to do it and not at all needed.
That said, for further efficiency you should hoist the clearing of ymm0 out of the loop. Something like this perhaps?
#include <immintrin.h>
#define N 1000
void fillMatrixByZeros(float matrix[N][N]){
for (int k = 0; k < N; k += 8){
for (int i = 0; i < N; ++i){
asm volatile (
"vmovups %1, %0"
: "=m"(matrix[i][k])
: "x"(_mm256_setzero_ps())
: "memory"
);
}
}
}
Note that just calling memset is likely to perform a lot better than hand-rolled inline assembly.
|
70,025,772 | 70,026,136 | How to find the closest palindrome to an integer? | I'm trying to write a program which can find the closest palindrome to an user-input integer
For example:
input 98 -> output 101
input 1234 -> output 1221
I know i have to transform the integer into string and compare the both halves but i have a hard time trying to start writing the code
I would appreciate any help!
Thanks!
| I think this is an acceptable solution:
#include <iostream>
#include <string>
int main( )
{
std::string num;
std::cout << "Enter a number: ";
std::cin >> num;
std::string str( num );
bool isNegative { };
if ( str[0] == '-' )
{
isNegative = true;
str.erase( str.begin( ) );
}
size_t sourceDigit { };
for ( size_t targetDigit = str.length( ) - 1; targetDigit >= str.length( ) / 2; --targetDigit, ++sourceDigit )
{
str[ targetDigit ] = str[ sourceDigit ]; // targetDigit is any digit from right-hand side half of the str that
// needs to be modified in order to make str a palindrome.
}
std::cout << "The closest palindrome to " << num << " is " << ( ( isNegative ) ? "-" : "" ) << str << '\n';
}
This supports numbers with a minus sign ('-') too. Hopefully, this will solve your issue. But please test it before using it.
|
70,025,846 | 70,026,689 | How to add new object to the array of objects in C++? | I have two classes, namely Players and Team In the Team class, I have array of Players instances, and the MAX_SİZE = 11
#define MAX 11
class Players{
// Some private and public members
};
class Team {
private:
Players players[MAX];
// Some other private and public members
};
I want to implement the addNewPlayer method in my Team class.
Whenever I call this method, I should be able to the add the name of the player to the end of this Players instances array, which is players. Now the function I consider is like :
void Team :: addNewPlayer(Players new_player){
// add new_player to the end of the array
}
I know the Stacks and Queues data structures as well. However, there is a restriction on using arrays only.
Is there any efficient way of adding new object to the array of objects in other class in general?
| players array is defined within Team class. To assign it a size; you use the variable MAX, if this variable uses an appropriate value, suppose one different from its maximum capacity that depends on the hardware, you can try creating a new array replacing the one of the class with a new length and element:
void Team::addNewPlayer(Players new_player) {
// add new_player to the end of the array
int newSize = sizeof(players)/sizeof(players[0]);
Players newArray[newSize+1];
for (int i=0; i < newSize; i++) {
newArray[i] = players[i];
}
newArray[newSize] = new_player;
players = newArray;
}
|
70,026,936 | 70,027,746 | Can an overloaded member function of a class depend on the outcome of an overloaded constructor of that class? | I have a class with an overloaded constructor where each version of the constructor initializes a different set of private attributes for that class. I also have a public member function of that class that will perform some operation based on the private attributes of that class. I want to overload the member function so that when I call it from the main function, it will execute an operation and return a value. Each operation will be different based on the exact outcome of the corresponding constructor. Is this possible? How could I implement this in C++? This is some incorrect code trying to express the idea:
class someClass {
double var1, var2, var3, var4, var5;
public:
someClass(double in1) {
// operations that initialize var1
}
someClass(double in1, double in2) {
// operations that initialize var1 and var2
}
someClass(double in1, double in2, double in3) {
// operations that initialize var1, var2 and var3
}
someClass(double in1, double in2, double in3, double in4) {
// operations that initialize var1, var2, var3 and var4
}
someClass(double in1, double in2, double in3, double in4, double in5) {
// operations that initialize var1, var2, var3, var4 and var5
}
double calcVal() {
return in1 + in3;
// this one is executed if the 1st constructor was called
}
double calcVal() {
return in1 + in2;
// this one is executed if the 2nd constructor was called
}
double calcVal() {
return in1 + in2 + in3;
// this one is executed if the 3rd constructor was called
}
double calcVal() {
return in1 + in2 + in3 + in4;
// this one is executed if the 4th constructor was called
}
double calcVal() {
return in1 + in2 + in3 + in4 + in5;
// this one is executed if the 5th constructor was called
}
}
| For me, this looks like inheritance with a virtual function.
struct someClass {
virtual ~someClass() {}
virtual double calcVal() = 0;
};
struct classWithVar1 : someClass {
double var1;
classWithVar1(double in1) : var1(in1) {}
double calcVal() override { return var1; }
};
struct classWithVar2 : someClass {
double var1, var2;
classWithVar2(double in1, double in2) : var1(in1), var2(in2) {}
double calcVal() override { return var1 + var2; }
};
/* etc. */
|
70,027,226 | 70,027,299 | C++ ensure object exists while executing a function | I have a function foo. During the execution of foo, I want to be certain that an object of type Bar exists. Let’s call whatever object that happens to be “bar.”
I cannot copy or move bar, and bar can have any storage duration. The one thing I do know about bar is that it is an empty object.
foo doesn't need to do anything with bar or know anything about it.
First thought is, pass a Bar& into foo to tell the calling environment, “hey, you need to make sure bar exists while I’m running!” But the calling environment could pass a dangling reference into foo, in which case bar would be destroyed before foo runs.
Second thought is, pass a shared_ptr to bar in. But (correct me if I’m wrong) this would require bar to have dynamic storage duration.
Third thought is, write a helper type that is copyable and movable that guarantees the existence of bar. But this feels like reinventing the shared_ptr wheel.
What are my options for ensuring bar exists during foo, and what are their strengths and limitations?
|
the calling environment could pass a dangling reference into foo
It really couldn't. Dangling references are not legal, so the only way for this to happen is by the caller violating the language rules. I don't find this a compelling concern.
pass a shared_ptr to bar in. But this would require bar to have dynamic storage duration.
Not quite. A shared_ptr can be constructed with a custom deleter, so if the caller wants to pass in a "stack allocated" Bar, they can construct a shared_ptr with a deleter which does not delete anything.
bar is that it is an empty object
Then what's the point of the entire exercise? Is it because the Bar constructor and/or destructor have side effects which must occur before/after foo runs? If that's the case, maybe foo should just do those things itself, or a foo_wrapper function can be created to hide these details.
|
70,027,304 | 70,028,829 | Is the following case an issue with the new C++ concept standard? | Consider this program which uses the curiously recurring template pattern:
template <typename T>
concept Frobulates = requires (T t) { t.frobulate(); };
template <typename Derived>
struct S {
int sidefumble() requires Frobulates<Derived> {
Derived::frobulate();
}
};
struct K: public S<K> {
void frobulate() {}
};
int main() {
K k;
k.sidefumble();
}
When compiled, it generates this error using clang++ version 13.0.0:
$ clang13 -std=c++20 ./recurring-concept.cpp -o recurring-concept && ./recurring-concept
./recurring-concept.cpp:17:7: error: invalid reference to function 'sidefumble': constraints not satisfied
k.sidefumble();
^
./recurring-concept.cpp:6:31: note: because 'K' does not satisfy 'Frobulates'
int sidefumble() requires Frobulates<Derived> {
^
./recurring-concept.cpp:2:41: note: because 't.frobulate()' would be invalid: no member named 'frobulate' in 'K'
concept Frobulates = requires (T t) { t.frobulate(); };
^
1 error generated.
Specifically, the compiler reports that the type K does not have a member frobulate(), but this is plainly false.
I would expect that sidefumble() is compileable, just as it would be if the requires statement were not present.
Is this expected/designed behavior? (It seems conceivable to me that possible use of the CRTP, being somewhat of an unusual corner case, might not have been accounted for in the design and/or implementation of this very young feature)
At the very least, the error message is badly misleading. Where is the appropriate place to start a discussion among compiler/standards authors about the handling of this case?
Is there a workaround?
| Looks like this is a bug.
Though this other question (thanks @T.C.) seems to outline slightly different scenario, the underlying bug seems to be the same.
This comment in a clang bug thread contains almost exactly the same repro.
|
70,027,356 | 70,159,228 | mutltithreading in C++ does not work with pybind11 to Python | I am having this difficulty to utilize the multithreading capability of C++ through python's pybind11 plugin system. I am aware of the notorious GIL issue and try to release it but no avail. Following is my C++ code:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "Calculator.h" // where run_calculator is
namespace py = pybind11;
// wrap c++ function with Numpy array IO
int wrapper(const std::string& input_file, py::array_t<double>& in_results) {
if (in_results.ndim() != 2)
throw std::runtime_error("Results should be a 2-D Numpy array");
auto buf = in_results.request();
double* ptr = (double*)buf.ptr;
size_t N = in_results.shape()[0];
size_t M = in_results.shape()[1];
std::vector<std::vector<double> > results;
pybind11::gil_scoped_release release;
run_calculator(input_file, results);
pybind11::gil_scoped_acquire acquire;
size_t pos = 0;
for (size_t i = 0; i < results.size(); i++) {
const std::vector<double>& line_data = results[i];
for (size_t j = 0; j < line_data.size(); j++) {
ptr[pos] = line_data[j];
pos++;
}
}
}
PYBIND11_MODULE(calculator, m) {
// optional module docstring
m.doc() = "pybind11 calculator plugin";
m.def("run_calculator", &wrapper, "Run the calculator");
}
Then on the python side:
results= np.zeros((N, M))
start = datetime.datetime.now()
run_calculator(input_file, results)
end = datetime.datetime.now()
elapsed = end - start
print(f'the calculation takes {elapsed.total_seconds()} seconds')
Basically the calculator takes in a file path, then return a 2-D array. I get this data passed back to python. In the calculator, I have multi-threading placed.
However, even with this pybind11::gil_scoped_release release, the runtime is not reduced at all. If I run on the C++ side using a main function to call run_calculator, the impact of multithreading is very obvious.
I also tried to declare the module to pybind11 in this way instead of using gil_scoped_release
PYBIND11_MODULE(calculator, m) {
// optional module docstring
m.doc() = "pybind11 calculator plugin";
m.def("run_calculator", &wrapper, py::call_guard<py::gil_scoped_release>());
}
However the run just crashes.
Anyone can point me to the right direction?
| This is a false alarm. The multithreading is working on the C++ side. GIL has nothing to do with that as long as the threading is not on the python side.
|
70,027,525 | 70,027,628 | Undefined reference to initialized static member variable with make_shared | Compiling with -std=c++14 the following code:
#include <memory>
class A
{
public:
static constexpr int c = 0;
std::shared_ptr<int> b;
A() {
b = std::make_shared<int> (c);
}
};
int main () {
A a;
return 0;
}
Gives a linker error "undefined reference to `A::c'", while using "A::c" in other contexts that are not "make_shared", this error doesn't occur. In particular, the following code compiles and works correctly:
class A
{
public:
static constexpr int c = 0;
std::shared_ptr<int> b;
A() {
int cc = c;
b = std::make_shared<int> (cc);
}
};
| Since C++17 the first code should work correctly: a static constexpr class member variable is implicitly inline which means the compiler takes care of making sure a definition exists .
Prior to C++17 the code has undefined behaviour (no diagnostic required) due to ODR violation. A static class member that is odr-used must also have an out-of-line definition.
Binding a reference to a variable counts as odr-use, and that happens with make_shared<int>(c) since that function is defined as :
template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );
so the argument is bound to a reference parameter.
In theory you should be able to work around it with make_shared<int>(+c) ... then the reference is bound to the temporary result of +c and not to c itself, therefore there is no odr-use. Similar theory to your posted workaround in the question.
enum { c = 0 }; is another possible workaround, if the type is int in the real code .
|
70,027,785 | 70,038,621 | Error build skia: machine type x64 conflicts with x86 | I'm trying to build Skia as per the instructions here https://skia.org/docs/user/build/. I install the C++ clang tools for Windows using the Visual Studio Installer and then configured skia as follows:
bin/gn gen out/Shared --args='clang_win="C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm" is_component_build=true is_debug=false is_official_build=true skia_use_system_expat=false skia_use_system_libjpeg_turbo=false skia_use_system_libpng=false skia_use_system_libwebp=false skia_use_system_zlib=false skia_use_system_icu=false skia_use_system_harfbuzz=false target_cpu="x64"'
Then I ran ninja -C out/Shared but during the build process I get the following error:
FAILED: skia.dll skia.dll.lib skia.dll.pdb
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm/bin/lld-link.exe" /nologo /IMPLIB:./skia.dll.lib /DLL /OUT:./skia.dll /PDB:./skia.dll.pdb @./skia.dll.rsp
lld-link: error: libcmt.lib(std_type_info_static.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(chkstk.obj): machine type x64 conflicts with x86
lld-link: error: libcpmt.lib(locale0.obj): machine type x64 conflicts with x86
lld-link: error: libcpmt.lib(thread0.obj): machine type x64 conflicts with x86
lld-link: error: libcpmt.lib(xthrow.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(delete_scalar_size.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(new_scalar.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(utility.obj): machine type x64 conflicts with x86
lld-link: error: libcpmt.lib(xlock.obj): machine type x64 conflicts with x86
lld-link: error: libcpmt.lib(locale.obj): machine type x64 conflicts with x86
lld-link: error: libcpmt.lib(iosptrs.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(guard_support.obj): machine type x64 conflicts with x86
lld-link: error: libcpmt.lib(syserror.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(gshandler.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(gshandlereh4.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(amdsecgs.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(gs_cookie.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(delete_scalar.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(throw_bad_alloc.obj): machine type x64 conflicts with x86
lld-link: error: libcmt.lib(cpu_disp.obj): machine type x64 conflicts with x86
lld-link: error: too many errors emitted, stopping now (use /errorlimit:0 to see all errors)
ninja: build stopped: subcommand failed.
I'm running a 64bit version of Windows 11.
Anyone have any idea on what the issue might be?
| Ok so it turns out that for some reason (not sure what), Skia has a problem with the LLVM version installed using the Visual Studio Installer. I downloaded LLVM directly from their official website and then ran:
bin/gn gen out/Shared --args='clang_win="C:\Program Files\LLVM" is_component_build=true is_debug=false is_official_build=true skia_use_system_expat=false skia_use_system_libjpeg_turbo=false skia_use_system_libpng=false skia_use_system_libwebp=false skia_use_system_zlib=false skia_use_system_icu=false skia_use_system_harfbuzz=false target_cpu="x64"'
Running this Skia builds without any errors.
|
70,028,017 | 70,030,357 | Exception has occured, unknown signal error when using class object again inside each function | I'm trying to write a C++ code for a course I'm enrolled in, where I keep the information of the students enrolled in the course.
I should be able to add a student to the classrrom in the user interface written in main , by calling the function void addNewStudent(int ID, string name, string surname), where I create my object instances, Student, and Course inside the function.
I should also be able to search by given ID by calling the function void showStudent(int ID) in the main, where the function uses the getStudent(ID) method of the object of the classCourse
I did not write all the methods, but when I try to debug this code, I got the error " Exception has occured, unknown signal error."
My questions are:
What is the reason of this error? How can I fix it?
Suppose that the user interface in the main is necessary to use as well as the functions it calls. Do I have to create a class object again inside each function as I wrote?
Can a more effective implementation be made in accordance with the object oriented principles I have defined above?
#include <iostream>
using namespace std;
#define MAX 10
class Student {
private:
int ID;
string name;
string surname;
public:
Student()
{
ID = 0;
string name = "" ;
string surname = "";
}
void setID(int ID_set);
int getID();
void setName(string name_set);
string getName();
void setSurName(string surname_set);
string getSurName();
};
class Course {
private:
Student students[MAX];
int num =0 ; // The current number of students in the course, initially 0.
float weightQ;
float weightHW;
float weightF;
public:
Course()
{
students[num] = {};
weightQ = 0.3;
weightHW = 0.3;
weightF = 0.4;
}
int getNum(); // Returns how many students are in the course
void addNewStudent(Student new_student);
void updateWeights(float weightQ_update, float weightHW_update, float weightF_update);
void getStudent(int ID_given);
};
// Method declerations for the class Student
void Student :: setID(int ID_set){
ID = ID_set;
}
int Student :: getID(){
return ID;
}
void Student :: setName(string name_set){
name = name_set;
}
string Student :: getName(){
return name;
}
void Student :: setSurName(string surname_set){
surname = surname_set;
}
string Student :: getSurName(){
return surname;
}
// Method declerations for the class Course
int Course :: getNum(){
return num;
}
void Course :: addNewStudent(Student new_student){
students[num] = new_student ;
num = num + 1;
}
void Course :: updateWeights(float weightQ_update, float weightHW_update, float weightF_update){
weightQ = weightQ_update;
weightHW = weightHW_update;
weightF = weightF_update;
}
void Course :: getStudent(int ID_given){
for(int i = 0; i<MAX; i++){
if(ID_given == students[i].getID()){
cout << "Student Name & Surname : " << students[i].getName() << " " << students[i].getSurName()<<"\n";
}
}
}
void addNewStudent(int ID, string name, string surname){
Student student;
Course ECE101;
student.setID(ID);
student.setName(name);
student.setSurName(surname);
ECE101.addNewStudent(student);
}
void showStudent(int ID){
Course ECE101;
ECE101.getStudent(ID);
}
int main(){
Course ECE101;
cout << "Welcome to the ECE101 Classroom Interface"<<"\n";
cout << "Choose your option\n";
string option_1 = "1) Add a student ";
string option_2 = "2) Search a student by ID";
cout << "Enter your option: ";
int x;
int ID;
string name, surname;
cin >> x;
if (x == 1)
cout << "Enter the student ID ";
cin >> ID;
cout << endl;
cout << "Enter the student name ";
cin >> name;
cout << endl;
cout << "Enter the student surname " ;
cin >> surname;
addNewStudent(ID, name, surname);
return 0;
}
| To make the menu more interactive you could add a do while statement that would accept 3 options:
register
show data
exit
int main(){
Course ECE101;
int x;
int ID;
string name, surname;
string option_1 = "1) Add a student\n";
string option_2 = "2) Search a student by ID\n";
cout << "Welcome to the ECE101 Classroom Interface\n";
cout << "Choose your option\n";
cout << option_1 << option_2;
cin >> x;
do {
if (x == 1) {
cout << "Enter the student ID ";
cin >> ID;
cout << endl;
cout << "Enter the student name ";
cin >> name;
cout << endl;
cout << "Enter the student surname " ;
cin >> surname;
addNewStudent(ID, name, surname, ECE101);
}
else {
cout << "Enter the student ID\n";
cin >> ID;
showStudent(ID, ECE101);
}
cout << "Choose your option\n";
cin >> x;
} while(x != 3);
return 0;
}
addnewStudent() and showStudent() methods now accepts an instance of Course as an argument to be able to add students.
void addNewStudent(int ID, string name, string surname, Course &course) {
Student student;
student.setID(ID);
student.setName(name);
student.setSurName(surname);
course.addNewStudent(student);
}
void showStudent(int ID, Course &course) {
course.getStudent(ID, course);
}
the function is modified from the same class as well.
void Course::getStudent(int ID_given, Course &course) {
for(int i = 0; i<MAX; i++){
if(ID_given == students[i].getID()){
cout << "Student Name & Surname : " << students[i].getName() << " " << students[i].getSurName()<<"\n";
}
}
}
Demo
|
70,028,107 | 70,028,206 | In C++, is "const_iterator" the same as "const iterator"? | Is a const_iterator the same as const iterator? if not what's the difference? if yes why does standard use const_iterator when const iterator is already meaningful?
For example, are these two declarations exactly the same ?
string& replace (const_iterator i1, const_iterator i2, const string& str);
string& replace (const iterator i1, const iterator i2, const string& str);
| No, they are not the same.
Like any const object, you can not make changes to a const iterator:
// ++it gives error below since we try to change it:
for(const std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {}
You are, however, allowed to change the value of the object a const iterator is pointing at:
// this is ok (assuming there is at least one element in the vector):
const std::vector<int>::iterator it = vec.begin();
*it = 10;
A const_iterator is mutable, but you can not change the object that the iterator is pointing at:
// ++it is ok below:
for(std::vector<int>::const_iterator it = vec.begin(); it != vec.end(); ++it) {
*it = 10; // error: `*it` is an `int const&`
}
With a const const_iterator, you can neither make changes to the iterator nor what it is pointing at.
const std::vector<int>::const_iterator it = vec.begin();
++it; // error
*it = 10; // error
std::cout << *it << '\n'; // ok
A constructed example to illustrate:
struct foo {
using const_iterator = char const*;
using iterator = char*;
const_iterator cbegin() const { return data; };
const_iterator cend() const { return data + sizeof data; };
const_iterator begin() const { return cbegin(); }
const_iterator end() const { return cend(); }
iterator begin() { return data; };
iterator end() { return data + sizeof data; };
char data[2];
};
As seen above, const_iterator and iterator are user defined type definitions. Only by convention are the names called what they are called. Using these conventional names also helpes when creating containers that are supposed to work well with other classes, since these type definitions are often used to create or specify instances/types. The names const_iterator and iterator do not give these alias any special properties though. It's all up to the creator of the class.
|
70,028,724 | 70,028,869 | C++ size_t in mixed arithmetic and logical operations | Currently using WSL2, g++, with -std=c++20 -Wall -Wextra -Wvla -Weffc++ -Wsign-conversion -Werror.
In the program I'm building, because I utilize several STL containers such as std::vector, std::array, std::string, etc, I've come across many situations involving integer arithmetic or logical comparisons between size_t (from .size() or .length()) and signed values.
To avoid errors from occuring, I have changed values (that "I think" should generally always be positive) into unsigned values, either by changing the variable definition, or using static_cast<size_t>() (which make my code lines especially long). But now I'm encountering more and more underflow errors.
Should I change all the variables back to signed types and use assertions to see if they go negative? What are some efficient ways to conduct integer arithmetic and logical comparisons between signed integers and unsigned integers (especially from .size())?
| Instead of calling the member function size(), you can use C++20 std::ssize() to get the signed size for comparison and operation with signed integers.
std::vector v{42};
auto size = std::ssize(v); // get signed size
|
70,028,924 | 70,028,963 | How is access of an index more than string's size in c++ allowed? | #include <iostream>
using namespace std;
int main() {
// your code goes here
string g = "12345";
cout << g[10] << endl; // Prints an empty character
return 0;
}
Reference: https://ideone.com/rpCWm2
This surprisingly works and doesn't throw an error! Can somebody explain how this is happening? Thank you!
| std::string g = "12345";
std::cout << g[10] << std::endl;
Your access is out-of-bounds, which makes it an undefined behaviour. Undefined behaviour can do anything, from running normally to crashing the program.
If you use the at() function instead(which does bound-checking), you will see that this will throw an std::out_of_range exception.
std::string g = "12345";
std::cout << g.at(10) << std::endl;
|
70,028,944 | 70,031,180 | How to handle runtime errors in C++? | So, I'm kinda new to C++ and I wanted to know what are the good practices or even how do I handle runtime errors when programming, here is an example:
State s_toState(std::string state){
if (state == "MG")
return State::MG;
else if (state == "PR")
return State::PR;
else if (state == "SP")
return State::SP;
else if (state == "SC")
return State::SC;
else if (state == "RJ")
return State::RJ;
else if (state == "RN")
return State::RN;
else if (state == "RS")
return State::RS;
// ???
}
So I have this function that transforms a string into a State. Without using exception, what is the ideal way for me to assert that the given state is an existing one (MG, PR, SP, etc...)?
Gave an example but I'm asking for the general rule. As far as I know i could use exceptions, assertions or just print the error. I do pretend to unit test this too (also new to unit testing and know nothing about it).
| Generally speaking, the way to handle such errors (like any errors) depends on the needs of your program as a whole - and you have not specified that. So there is no one-size-fits-all "general rule".
There are options and trade-offs.
One option is for your State enumerated type to provide an enumerator value that represents undetermined or an invalid state, such as
enum class State {MG, PR, Undetermined};
Then, in your function, return the undetermined value, e.g.
State s_toState(const std::string &state)
{
State return_value = State::Undetermined;
if (state == "MG")
return_value = State::MG;
else if (state == "PR")
return_value = State::PR;
// etc
return return_value;
}
With this approach the function always returns a valid value of type State. If the error conditions aren't critical (i.e. the program can continue if an invalid string is supplied) then the caller can decide if it needs to check the return value. Multiple types of error condition can be reported (e.g. by having multiple enum values representing different errors) A down-side is that the caller may forget to check the return value and behave incorrectly.
Another option is to throw an exception, for example;
State s_toState(const std::string &state)
{
if (state == "MG")
return State::MG;
else if (state == "PR")
return State::PR;
// etc
throw std::invalid_argument("Bad input string");
}
This option requires some sensible choice of what type of exception to throw (e.g. what information needs to be conveyed about the error state). This approach may be preferable if the caller (or the program as a whole) cannot sensibly continue if a bad string is provided since, by throwing an exception, the caller is forced to catch and take any recovery action to avoid being terminated. As such, this approach may not be suitable for non-critical errors - for example, if execution can sensibly continue if a bad string is provided.
Another option (C++17 and later) is to return std::optional<State>. This allows the caller to check if an error has occurred (e.g. std::option::has_value() return false) occurs or, if the value is accessed without checking, cause an exception of type std::bad_optional_access to be thrown (which may be suitable for the caller, or may be uninformative).
It's also possible to use assert() - which forces termination if a specified condition is untrue. Generally, I prefer throwing an exception over using assert() but you may prefer otherwise.
|
70,029,205 | 70,029,273 | Declare a variable and return it in the same line C++ | I have code that does
if(x>5){
vector<int> a;
return a;
}
But i'm curious if theres a way to do this return in one line such like:
if(x>5){
return vector<int> a;
}
| This will work as expected:
return vector<int>();
This creates an object and returns one at the same time. Since the object has not been created without any name, it is known as anonymous object.
Hence you can modify your code, without assigning a name to the variable, like this:
if(x>5){
return vector<int>();
}
|
70,029,743 | 70,030,360 | Overload inherited methods in an Rcpp class | I have two classes A, the parent and B, the child.
B overloads a method from A. The problem is that the method getval is not overloaded when exposing class B in an RCPP module, despite explicitly exposing it again a second time with a pointer to B::getval.
Is it due to a bug in Rcpp, a limitation or something I just don't know yet?
class A
{
public:
A(int val) : val(val) {}
int getval()
{
Rcout << "I am A" << endl;
return val;
}
private:
int val;
};
class B : public A
{
public:
using A::A;
int getval()
{
Rcout << "I am B" << endl;
return A::getval();
}
};
RCPP_MODULE(rg)
{
using namespace Rcpp;
class_<A>("A")
.constructor<int>()
.method("getval", &A::getval);
class_<B>("B")
.derives<A>("A")
.constructor<int>()
.method("getval", &B::getval);
}
| If I use my basic example above (in the question) in a simple C++ program as follows:
int main()
{
A a(42);
B b(43);
cout << a.getval() << endl;
cout << b.getval() << endl;
}
the correct method will be used. However, with Rcpp, the parent class A must declare the method getval as virtual:
virtual int getval()
In fact, it's good to declare the same method in B as virtual too. In R, it will finally work as expected:
a <- A$new(42)
b <- B$new(43)
Then:
a$getval()
I am A
[1] 42
b$getval()
I am B
I am A
[1] 43
Note that the message I am A under I am B is expected because in my example I do an explicit call the A::getval.
|
70,029,939 | 70,030,057 | Set the working directory when starting a process with boost | I am looking for a way to specify the working directory when starting a process with boost::process::system or boost::process::child. In the docs https://www.boost.org/doc/libs/1_77_0/doc/html/boost_process/tutorial.html are some useful examples, but nothing on the subject of my interest.
The child constructor looks like this:
template<typename ...Args>
child::child(Args&&...args)
and I haven't found complete documentation covering what the Args might be, only some incomplete examples.
| #include <boost/process/start_dir.hpp>
namespace bp = boost::process;
int result = bp::system("/usr/bin/g++", "main.cpp", bp::start_dir("/home/user"));
bp::child c(bp::search_path("g++"), "main.cpp", bp::start_dir("/home/user"));
c.wait();
See boost::process::start_dir and the complete Reference.
Args are program name, program args and other process properties from the Reference.
|
70,030,015 | 70,030,033 | Why does an error occur when I modulus the value in array? | may i know what exactly have gone wrong in this code? cause the output of the even number is not what i expected if i input the value in the comment
//int number[10]={0, 2, 5, 8, -2, 0, 6, 4, 3, 1};
int number[10], divided_number[10], total_odd_numbers, total_even_numbers, a;
for(int i=0;i<=9;i++){
a=i+1;
cout<<"Number "<<a<<": ";
cin>>number[i];
}
for(int i =0; i<=9; i++){
cout<<*(number+i)<<" ";
}
cout<<endl;
for(int i=0;i<=9; i++){
divided_number[i]=number[i]%2;
if(divided_number[i]!=0){
total_odd_numbers +=1;
}
else if (divided_number[i]==0){
total_even_numbers++;
}
}
for(int i=0;i<=9; i++){
cout<<*(divided_number+i)<<" ";
}
cout<<"\n Total odd number: "<<total_odd_numbers<<endl;
cout<<"\n Total even number: "<<total_even_numbers<<endl;
| The problem is that total_odd_numbers and total_even_numbers are not initialized before being accessed. This is called undefined behavior. In this case, the program will take whichever trash data is already in the memory assigned to those variables and just use it as-is (and so, of course, the output may or may not be correct, depends on what's in that memory at the time of assignment).
It should be noted that :
Using an unitialized value is, by itself, not undefined behavior, but the value is simply indeterminate. Accessing this then is UB if the value happens to be a trap representation for the type. Unsigned types rarely have trap representations, so you would be relatively safe on that side.
Modified program:
#include <iostream>
using namespace std;
int main()
{
int number[10]={0, 2, 5, 8, -2, 0, 6, 4, 3, 1};
int divided_number[10], total_odd_numbers = 0, total_even_numbers = 0, a;
for(int i =0; i<=9; i++){
cout<<*(number+i)<<" ";
}
cout<<endl;
for(int i=0;i<=9; i++){
divided_number[i]=number[i]%2;
if(divided_number[i]!=0){
total_odd_numbers +=1;
}
else if (divided_number[i]==0){
total_even_numbers++;
}
}
for(int i=0;i<=9; i++){
cout<<*(divided_number+i)<<" ";
}
cout<<"\n Total odd number: "<<total_odd_numbers<<endl;
cout<<"\n Total even number: "<<total_even_numbers<<endl;
}
Output:
0 2 5 8 -2 0 6 4 3 1
0 0 1 0 0 0 0 0 1 1
Total odd number: 3
Total even number: 7
And, of course, the code could be cleaned up much further:
int number[10]={0, 2, 5, 8, -2, 0, 6, 4, 3, 1};
int odds = 0, evens = 0;
for(int i=0;i<=9; i++)
{
int left = number[i] % 2; cout << left << " ";
if (left != 0) {odds++;} else {evens++;}
}
cout<<"\nTotal odd number: "<<odds<<'\n'<<"Total even number: "<<evens;
Further reading:
(Why) is using an uninitialized variable undefined behavior?
https://en.cppreference.com/w/cpp/language/ub
And also:
Why is "using namespace std;" considered bad practice?
|
70,030,906 | 70,031,122 | I want my zeros to be some other number/character (C++) | double floaty=36.6736872;
cout<<fixed<<setprecision(10)<<floaty;
My output is "36.6736872000";
I want my zeros to be some other number.
Eg: If I want zeros to be ^.
then the output should be 36.6736872^^^
I don't have any idea other than using setw and setfill to get my desired output in single line of code
| You can use std::ostringstream, and change the resulting string in any way you see fit:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
int main()
{
double floaty=36.6736872;
std::ostringstream strm;
// Get the output as a string
strm << std::fixed << std::setprecision(10) << floaty;
std::string out = strm.str();
// Process the output
auto iter = out.rbegin();
while (iter != out.rend() && *iter == '0')
{
*iter = '^';
++iter;
}
std::cout << out;
}
Output:
36.6736872^^^
|
70,030,927 | 70,031,130 | How to generate program code from ui-forms? | I have a UI, generated with Qt Designer. It's generates me a XML code like these:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ColorDialog</class>
<widget class="QDialog" name="ColorDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
and etc
I want to remove this UI and edit a view by C++ code like these:
for (auto button:m_buttonColorsList)
{
m_colorsLayout->addWidget(button);
}
m_mainGroupBox->setLayout(m_colorsLayout);
m_mainLayout->addWidget(m_mainGroupBox);
setLayout(m_mainLayout);
How I can convert the exiting form to code?
| If you want to generate code using the .ui information then you must use uic tool:
uic filename.ui -g cpp -o filename_ui.h
|
70,030,985 | 70,031,263 | How to pass the target function of std::thread constructor as an argument | I can do this to start my thread:
int main_test() {
// do something...
return 0;
}
std::thread* myThread;
void myFunction() {
myThread = new std::thread(main_test);
}
How do I pass main_test as an argument to myFunction, so the same function can be used to start the thread using different target functions? What would the signature of myFunction be then?
I guess what I don't understand is how the templated version of the std::thread constructor is invoked with a specified type.
|
How do I pass main_test as an argument to myFunction, so the same function can be used to start the thread using different target functions?
You can pass the poiter to your function as an argument
void myFunction(int (*func)()) {
myThread = new std::thread(func);
}
int callSelector(int someCriteria)
{
if (someCriteria == 0) {
myFunction(main_test1);
}
else {
myFunction(main_test2);
}
}
|
70,031,324 | 70,031,422 | Difference between char in C and C++? | I know that C and C++ are different languages.
Code - C
#include <stdio.h>
int main()
{
printf("%zu",sizeof('a'));
return 0;
}
Output
4
Code- C++
#include <iostream>
int main()
{
std::cout<<sizeof('a');
return 0;
}
Output
1
https://stackoverflow.com/a/14822074/11862989 in this answer user Kerrek SB(438k Rep.) telling about types in C++ nor mentions char neither int but just integral.
is char in C++ is integral type or strict char type ?
|
is char in C++ is integral type or strict char type ?
Character types, such as char, are integral types in C++.
The type of narrow character constant in C is int, while the type of narrow character literal in C++ is char.
|
70,031,459 | 70,031,805 | Error when trying to serialize std::wstring with boost::serialization | I'm trying to serialize a class with a std::wstring variable, but what I'm getting are multiple undefined reference to ~ errors.
I don't seem to be missing any headers or libraries & from what I've read from the boost::serialization documents, std::wstring seems to be a primitive type that doesn't need any overriding.
I've included the following headers:
#include <boost/archive/text_woarchive.hpp>
#include <boost/archive/text_wiarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include <locale>
The class I'm trying to serialize looks like this:
class A
{
public:
A() = default;
void setWstr(const std::wstring &wstr)
{
wstr_ = wstr;
}
const std::wstring &getWstr()
{
return wstr_;
};
private:
std::wstring wstr_;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar &boost::serialization::make_nvp("wstr", wstr_);
}
};
int main()
{
std::wstring sdn = L"src dept";
A test;
test.setWstr(sdn);
std::wstringstream ss;
boost::archive::text_woarchive oa(ss);
oa << test;
return 0;
}
The errors I'm getting are these:
in function `text_woarchive_impl':
undefined reference to `boost::archive::basic_text_oprimitive<std::basic_ostream<wchar_t, std::char_traits<wchar_t> > >::basic_text_oprimitive(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >&, bool)'
in function `text_woarchive_impl':
undefined reference to `boost::archive::basic_text_oarchive<boost::archive::text_woarchive>::init()'
`~text_woarchive_impl':
undefined reference to `boost::archive::basic_text_oprimitive<std::basic_ostream<wchar_t, std::char_traits<wchar_t> > >::~basic_text_oprimitive()'
Is there a way to fix this?
ETA) I've linked the following libraries
-lboost_serialization -lpthread -lboost_system -lboost_program_options -lboost_chrono
| The serialization objects are split into two libraries: boost_serialization (which you are linking against) and the corresponding objects for wchar etc. in boost_wserialization. So, you need to add -lboost_wserialization to your linker flags.
|
70,031,982 | 70,032,089 | My Bubble Sort Program worked for one case but not for other. How this is Possible? | #include<iostream>
using namespace std;
int main(){
int n;
cout<<"Enter size of array-";
cin>>n;
int arr[n];
cout<<"Enter all elements"<<endl;
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"Your Entered elements are"<<endl;
for(int i=0;i<n;i++){
cout<<arr[i]<<",";
}
cout<<endl;
for(int x=0;0<n-x;x++){
for(int i=0;i<n;i++){
if(arr[i]>arr[i+1]){
int tem=arr[i];
arr[i]=arr[i+1];
arr[i+1]=tem;
}
}
}
cout<<"Sorted Array"<<endl;
for(int i=0;i<n;i++){
cout<<arr[i]<<",";
}
return 0;
}
For first case
Enter size of array-6
Enter all elements
4 5 3 2 1 9
Your Entered elements are
4,5,3,2,1,9,
Sorted Array
1,2,3,4,5,9,
For second case(This have Problem)
Enter size of array-4
Enter all elements
20
40
30
50
Your Entered elements are
20,40,30,50,
| You are trying to access arr[i+1]. When i = n-1, arr[i+1] = arr[n], so your access is out-of-bounds.
Also, int arr[n] isn't valid C++. You should use std::vector<int> instead.
|
70,032,111 | 70,032,496 | How to pass and start multiple threads within a function? | I want to pass in an arbitrary number of functions together with their arguments to a function called startThread so that it can run them concurrently.
My code is below but obviously, it has syntactic errors:
#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <exception>
int test1( int i, double d )
{
// do something...
using namespace std::chrono_literals;
std::this_thread::sleep_for( 3000ms );
return 0;
}
int test2( char c )
{
// do something...
using namespace std::chrono_literals;
std::this_thread::sleep_for( 2000ms );
return 0;
}
template< class Fn, class... Args > // how should I write the template and startThread params to
int startThread( Fn&&... fns, Args&&... args ) // get arbitrary functions as threads and their own arguments?
{
std::vector< std::thread > threads;
threads.push_back( std::thread( test1, 2, 65.2 ) ); // how to automate the task of starting the
threads.push_back( std::thread( test2, 'A' ) ); // threads instead of writing them one by one?
std::cout << "synchronizing all threads...\n";
for ( auto& th : threads ) th.join();
return 0;
}
int main( )
{
int successIndicator { };
try
{
successIndicator = startThread( test1( 2, 65.2 ), test2( 'A' ) ); // what should be passed to startThread?
} // How to pass the arguments?
catch ( const std::exception& e )
{
successIndicator = -1;
std::cerr << e.what( ) << '\n';
}
return successIndicator;
}
Thanks in advance.
| This is how I would do it, using a recursive template function.
And std::async instead of std::thread
#include <future>
#include <chrono>
#include <thread>
#include <iostream>
void test1(int /*i*/, double /*d*/)
{
std::cout << "Test1 start\n";
std::this_thread::sleep_for(std::chrono::milliseconds(300));
std::cout << "Test1 done\n";
}
void test2(bool)
{
std::cout << "Test2 start\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "Test2 done\n";
}
//-----------------------------------------------------------------------------
// Recursive template function that will start all passed functions
// and then waits for them to be finished one by one.
// this will still be limited by the slowest function
// so no need to store them in a collection or something
template<typename Fn, typename... Fns>
void run_parallel(Fn fn, Fns&&... fns)
{
// I prefer using std::async instead of std::thread
// it has a better abstraction and futures
// allow passing of exceptions back to the calling thread.
auto future = std::async(std::launch::async, fn);
// are there any more functions to start then do so
if constexpr (sizeof...(fns) > 0)
{
run_parallel(std::forward<Fns>(fns)...);
}
future.get();
}
//-----------------------------------------------------------------------------
int main()
{
std::cout << "main start\n";
// start all functions by creating lambdas for them
run_parallel(
[]() { test1(1, 1.10); },
[]() { test2(true); }
);
std::cout << "main done\n";
}
|
70,032,585 | 70,032,678 | Using a method in the created Window in QT | Right now, there is a button for activating the function, like:
Window {
id: window
width: Screen.width
height: Screen.height
visible: true
property alias originalImage: originalImage
title: qsTr("Window1")
Button{
id: startButton
x: 50
y:100
text: "Open"
onClicked: {
VideoStreamer.openVideoCamera()
}
}
But I want to activate this method just after the window is created, not with a button click. Like
Window {
id: window
width: Screen.width
height: Screen.height
visible: true
property alias originalImage: originalImage
title: qsTr("Window1")
VideoStreamer.openVideoCamera()
}
But it doesn't work like that. I get expected token ":" error. It expects something like somecondition: How am I going to manage this without a button, or without an external user-needed condition like onclicked:, etc. ?
| You can use Component.onCompleted signal to do things right after component is created.
The onCompleted signal handler can be declared on any object. The order of running the handlers is undefined.
Window {
id: window
width: Screen.width
height: Screen.height
visible: true
property alias originalImage: originalImage
title: qsTr("Window1")
Component.onCompleted:
{
VideoStreamer.openVideoCamera()
}
}
P.S.: if your VideoStreamer is an QML object maybe it is a better to use this signal directly there.
|
70,032,640 | 70,032,840 | How to check the value of a bit in C++ | I would like to check the value of the 5th and the 4th bit starting from the left in this strings like this one:
value: "00001101100000000000000001000110"
value: "00000101100000000000000001000110"
value: "00010101100000000000000001000110"
The value is generated as a string in this way:
msg.value = bitset<32>(packet.status()).to_string();
to be sent a a ROS node and I receive it as a string.
Can I still use bitset to check the value of the bits even if it is a string?
What is the best solution to check them?
| You don't have a bitset, you have a string, in which each "bit" is represented by a char.
To check the 4th and 5th "bits", just use:
msg.value[3] != '0' and msg.value[4] != '0'
msg.value[3] & 1 and msg.value[4] & 1
#2 might be faster; it exploits the fact that '0' and '1' differ in the lowest bit only.
|
70,032,994 | 70,037,065 | CMake - 3rdparty folder and mulit module project | What is good practice to create 3rdparty folder?
I have a project with multiple modules that are in scope of project, some of those modules are depending on 3rdpartys. Currently I have single 3rdparty folder in root. On top of that I've created cmake folder with Find<package>.cmake files. Then each module just call find_package if lib is necessary.
Question is if that's a good practice? Each module should have his own 3rdparty folder or now how it is currently is just fine?
To extend scope of question - I have a 3rdparty which I would like to debug.
- root/
- 3rdparty/
- 3rdplib/
- mylib/
- CmakeLists.txt
...
add_subdirectory sounds like nice option but 3rdplib is not in same folder as mylib.
| I would say that what you have done is the cleanest possible way of managing 3rd party dependencies in a multi-component project.
What you presented matches perfectly the "external" directory of the Pitchfork proposal (which aims to establish/standarize typical C/C++ project structure).
|
70,033,024 | 70,033,478 | leetcode 295 median in stream, runtime error? | Leetcode 295 is to find median in a data stream.
I want to use two heaps to implement it. which can make add a data from stream in O(logn), get the percentile in O(1).
left_heap is a min_heap which used to save the left data of requied percentile.
right_heap used to save data which is larger than percentile.
In class SortedStream, which can make add data o(logn) and make findMedian o(1)
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
using namespace std;
class SortedStream {
public:
SortedStream(double percent, size_t rsize = 65536*16) : percent_(percent), reserve_size_(rsize) {
init();
}
void push(double v) { // time complexity, o(logn)
++size_;
double left_top = left_data_.back();
if (left_data_.empty() || v <= left_top) { left_data_.push_back(v); std::push_heap(left_data_.begin(), left_data_.end(), std::less<double>{}); }
else { right_data_.push_back(v); std::push_heap(right_data_.begin(), right_data_.end(), std::greater<double>{}); }
size_t idx = size_ * percent_ + 1;
size_t left_size = left_data_.size();
if (idx < left_size) {
// pop left top into right
std::pop_heap(left_data_.begin(), left_data_.end(), std::less<double>{});
double left_top = left_data_.back();
left_data_.pop_back();
right_data_.push_back(left_top);
std::push_heap(right_data_.begin(), right_data_.end(), std::less<double>{});
} else if (idx > left_size) {
// pop right top into left
std::pop_heap(right_data_.begin(), right_data_.end(), std::greater<double>{});
double right_top = right_data_.back();
right_data_.pop_back();
left_data_.push_back(right_top);
std::push_heap(left_data_.begin(), left_data_.end(), std::greater<double>{});
}
}
void init() {
size_t lsize = reserve_size_ * percent_ + 2;
left_data_.reserve(lsize);
right_data_.reserve(reserve_size_ - lsize + 2);
max_ = INT_MIN;
min_ = INT_MAX;
std::make_heap(left_data_.begin(), left_data_.end(), std::less<double>{});
std::make_heap(right_data_.begin(), right_data_.end(), std::greater<double>{});
size_ = 0;
}
size_t size() const { return size_; }
double max() const { return max_; }
double min() const { return min_; }
double percentile() const { // time complexity o(1)
return left_data_.back();
}
public:
double percent_;
size_t size_;
double max_, min_;
std::vector<double> left_data_, right_data_;
size_t reserve_size_;
};
class MedianFinder {
public:
MedianFinder() : ss(0.5){}
void addNum(int num) {ss.push(num);}
double findMedian() {return ss.percentile();}
SortedStream ss;
};
int main() {
MedianFinder* obj = new MedianFinder();
for (size_t i = 0; i< 15; ++i) {
obj->addNum(i);
double param_2 = obj->findMedian();
cout << "i = " << i << " median = " << param_2 << endl;
}
}
it's ok to run in my laptop, but when i submit in leetcode, it comes out:
Line 863: Char 45: runtime error: applying non-zero offset 18446744073709551608 to null pointer (stl_iterator.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_iterator.h:868:45
I never see this error.
can you help on this?
| You have one minor problem
In the line
double left_top = left_data_.back();
At the very beginning, the std::vector "left_data" will be empty. If you try to access the last element of an empty vector, you will get an runtime error.
If you modify this line to for example:
double left_top = left_data_.empty()?0.0:left_data_.back();
Then your program will work as you expect it to work.
I personally find the approach a a little bit too complicated. Maybe you could use a std::multiset or a std::priority_queue. Especially the std::priority_queue will also implement a max-heap and a min-hep for you, without out the overhead of calling std::vectors heap functions.
But I am still in favor of the std::multiset . . .
|
70,033,277 | 70,033,621 | How to use modulo 10^9+7 | I am trying to write a code for sum of square of natural numbers but with mod it's giving wrong answer. What would be the correct way here?
#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
int main()
{
int N;
cin>>N;
cout<< (((N) * (N+1) * (2*N+1))/6)%mod;
return 0;
}
| (N) * (N+1) * (2*N+1) can be, even if N is less than 1000000007, too large. Namely up to 2000000039000000253000000546, which is an 91-bit number. It is not likely that int on your system is capable of containing such large numbers.
As usual with this type of question, the work-around is a combination of:
Using a larger integer type for intermediate products, and
Applying modulo reduction on intermediate products, not only at the end.
Using just one of them is not sufficient.
As a consequence of applying modulo reduction earlier, the division by 6 will not work with a normal division, it will have to be a multiplication by the modular multiplicative inverse of 6 mod 1000000007, which is 166666668.
Example code:
mod_mul(mod_mul(mod_mul(N, N + 1, mod), mod_mul(2, N, mod) + 1, mod), inv6, mod)
Using some suitable definition of mod_mul, which can avoid overflow by using long long or a similar type.
|
70,033,337 | 70,033,462 | Retrieve first key of std::multimap, c++ | I want to retrieve just the first key of a multimap. I already achieved it with iterating through the multimap, taking the first key and then do break. But there should be a better way, but I do not find it.
int store_key;
std::multimap<int, int> example_map; // then something in it..
for (auto key : example_map)
{
store_key = key;
break;
}
This solves the Problem, but I am searching for another solution.
| Your range based for loop is more or less (not exactly but good enough for this answer) equivalent to:
for (auto it = example_map.begin(); it != example_map.end(); ++it) {
auto key = *it;
store_key = key;
break;
}
I hope now it is clear that you can get rid of the loop and for a non-empty map it is just:
auto store_key = *example_map.begin();
Note that store_key is a misnomer, because it is not just the key and your code would trigger a compiler error. It is a std::pair<const int,int>. store_key->first is the key.
|
70,033,455 | 70,034,522 | Devlop programme by Qt LGPL 4d1,must by section 6 of the GNU GPL. So that must provide All Source Code? | I want develop a gratis software use Qt,I read the LPGL. I want by 4d1.But must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. If by GNU GPL 6, must provide All Source Code.
Just dynamically link to Qt. If you dynamically link to LGPL libraries, there's nothing to worry about.
@Cornstalks
But Qt LGPL say that:
If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
The 4d1:
Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
And The GNU GPL
GNU GPL
The section 6's mean is Provide All Source Code.
| LGPL 4e says
If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
Section 6 defines "installation information" as follows:
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
Which, in the case of an LGPL library, boils down to telling people how to replace the Qt DLLs with other ones.
|
70,033,985 | 70,035,718 | How does .Byte[] function on a specific byte? | I am working on the following lines of code:
#define WDOG_STATUS 0x0440
#define ESM_OP 0x08
and in a method of my defined class I have:
bool WatchDog = 0;
bool Operational = 0;
unsigned char i;
ULONG TempLong;
unsigned char Status;
TempLong.Long = SPIReadRegisterIndirect (WDOG_STATUS, 1); // read watchdog status
if ((TempLong.Byte[0] & 0x01) == 0x01)
WatchDog = 0;
else
WatchDog = 1;
TempLong.Long = SPIReadRegisterIndirect (AL_STATUS, 1);
Status = TempLong.Byte[0] & 0x0F;
if (Status == ESM_OP)
Operational = 1;
else
Operational = 0;
What SPIReadRegisterInderect() does is, it takes an unsigned short as Address of the register to read and an unsigned char Len as number of bytes to read.
What is baffling me is Byte[]. I am assuming that this is a method to separate some parts of byte from the value in Long ( which is read from SPIReadRegisterIndirect ). but why is that [0]? shouldn't it be 1? and how is that functioning? I mean if it is isolating only one byte, for example for the WatchDog case, is TempLong.Byte[0] equal to 04 or 40? (when I am printing the value before if statement, it is shown as 0, which is neither 04 nor 40 from WDOG_STATUS defined register.)
Please consider that I am new to this subject. and I have done google search and other searchs but unfortunatly I could not found what I wanted. Could somebody please help me to understand how this syntax works or direct me to a documentation where I can read about it?
Thank you in advance.
| Your ULONG must be defined somewhere.
Else you'd get the syntax error 'ULONG' does not name a type
Probably something like:
typedef union {unsigned long Long; byte Byte[4];} ULONG;
Check union ( and typedef ) in your C / C++ book, and you'll see that
this union helps reinterpreting the long variable as an array of bytes.
Byte[0] is the first byte. Depending on the hardware (avr controllers are little endian) it's probably the LSB (least significant byte)
|
70,034,027 | 70,175,629 | How do I read data via i2c from a MAX11613 chip using C++ on a RPI 3B+ | I'm trying to write a driver for a MAX11613 ADC chip (MAX11613 Datasheet) in c++. I think I've got the write code correct for the setup and config, but I'm having some trouble with the read code. I am setting the chip up to read using the internal clock in Unipolar mode and the internal voltage reference, then writing the config to scan using AIN0 as the + signal and AIN1 as the - signal channels and report the differential reading. It does seem to read data, though the data appears to be very erratic and not what is anticipated based on oscilloscope results.
Setup bits: //1111 0000=0xF0 SEL2=1, SEL1=1, SEL0=1, INTERNAL CLOCK, UNIPOLAR
Config bits: //0110 0000=0x60 SCAN1=1, SCAN0=1, AIN0-AIN1, DIFFERENTIAL
Here's my read code, which may be part of the problem:
static uint16_t readMAXRegister(uint8_t i2cAddress, uint8_t reg) {
unsigned char buff[16];
beginMAXTransmission(i2cAddress);
i2c_smbus_read_i2c_block_data(i2cMAXHandle, reg, 16, buff);
endMAXTransmission();
uint16_t res = (buff[1] << 8) + buff[0];
return res;
}
int16_t MAX11613::readMAXADC_Differential_0_1() {
// Write config register to the ADC
writeMAXRegister(m_i2cAddress, MAX_WRITE, MAX_CONFIG);
// Wait for the conversion to complete
usleep(m_conversionDelay);
// Read the conversion results
uint16_t res = readMAXRegister(m_i2cAddress, 1) >> m_bitShift;
// Shift 12-bit results right 4 bits
res = (res >> 11) == 0 ? res : -1 ^ 0xFFF | res;
std::bitset<12> y(res);
std::cout << "READ RESULT " << y << " " << res << std::endl;
return (int16_t)res;
}
| It appears that I am now able to read data from the device after some more review. Here's the final code that works, for anyone else that might be interested.
static void writeMAXRegister(uint8_t i2cAddress, uint8_t reg, uint8_t value) {
beginMAXTransmission(i2cAddress);
i2c_smbus_write_word_data(i2cMAXHandle, reg, payload);
endMAXTransmission();
uint8_t payload = value;
}
static uint16_t readMAXRegister(uint8_t i2cAddress, uint8_t reg) {
const uint8_t datalength = 2;
unsigned char data[datalength];
beginMAXTransmission(i2cAddress);
i2c_smbus_read_i2c_block_data(i2cMAXHandle, reg, datalength, data);
endMAXTransmission();
uint16_t res =((data[0]&0xF)<<8)+data[1];//<---THIS READS 16 BITS AND REMOVES FIRST 4 '1111' BITS OF DATA
return res;
}
|
70,034,244 | 70,034,322 | Reading dynamic matrix from file with unspecified number of columns | This method is creating my dynamic allocated matrix that I have to read it from a file. I managed finding the columns for every row from the file and initialize my matrix, but I don't know how to read now the values and introduce them into the matrix.
The number of neighbourhoods(noCartiere) is generated random from 2 to 14. The number of rows is "noCartiere", the columns is "noStrazi" and "noLocuitori" are the values from the txt file.
void alocaTablou(int& noCartiere, int& noStrazi, int**& noLocuitori)
{
srand(time(NULL));
noCartiere = rand() % 13 + 2;
cout << "noCartiere generat random este: " << noCartiere << endl;
ifstream f("Text.txt");
string line, word;
noLocuitori = new int* [noCartiere];
int i = 0;
while (getline(f, line))
{
noStrazi = 0;
istringstream iss(line, istringstream::in);
while (iss >> word)
{
noStrazi++;
}
noLocuitori[i] = new int[noStrazi];
i++;
}
}
My Text.txt is:
499 50 79 300
76 89
10 80 80 10 10
689 78 202 34
976 234 566 80
877 590 23 10 10 10
30 59 73 189 200 500 600 700
| The solution is to use vectors. More specifically a vector of vectors of integers: std::vector<std::vector<int>>.
Using vectors, you can also skip the inner reading loop completely, and instead use std::istream_iterator to initialize (and add) the inner vector directly.
Something like this:
std::vector<std::vector<int>> noLocuitori;
std::string line;
while (std::getline(f, line))
{
std::istringstream iss(line);
noLocuitori.emplace_back(std::istream_iterator<int>(iss),
std::istream_iterator<int>());
}
|
70,034,503 | 70,034,590 | How to build a class in C++ to use in Python? | PyMethodDef from Python.h allows to specify Cpp-built functions to use in Python. However, there is much doubt if this can be applied for Cpp-built classes and I can't find anything like PyClassDef which could presumably help me to do so. All I've managed to find concerns class methods, but not the class itself. Is it possible to build a class in C++ with regular Python-C-API to use as a regular class in Python?
| You can use pybind11 to implement python call c++ native class.
Link here pybind11 class
it's easier use than cpython.
|
70,034,513 | 70,034,558 | move from unique_ptr to stack variable | Is it possible to create a stack variable (of type T with a move constructor) from a std::unique_ptr<T>?
I tried something like
std::unique_ptr<T> p = ext_get_my_pointer(); // external call returns a smart pointer
T val{std::move(*p.release())}; // I actually need a stack variable
but it looks ugly, and creates a memory leak apparently. Not sure why though.
| It is a memory leak because you have decoupled the allocated memory from the unique_ptr, but it is still allocated.
Assuming you have a functioning move constructor, why not:
std::unique_ptr<T> p = ext_get_my_pointer();
T val{std::move(*p)};
// p goes out of scope so is freed at the end of the block, or you can call `p.reset()` explicitly.
|
70,034,915 | 70,035,014 | Is it necessary to check range in bit representation C++ | Some data are stored in a 64 bit integer. As you can see, inside the getDrvAns function I check if the bit in the position drvIdx-1 is 0 or 1. One cannot be sure if the drvIdx will have a value in the right range (1-64). However, I noticed that if we put a value higher that 64, we have a wrap-around effect as demonstrated in the code below.
My question is, is this a standard behavior? Is it safe to leave it as it is without boundary checks?
Note: If the bit is set to 0 the drive has answered.
uint64_t mDrvAns = 48822;
bool getDrvAns(int drvIdx) {
std::bitset<64> bitRepOfmDrvAns{mDrvAns};
return (bitRepOfmDrvAns[drvIdx - 1] != 0ull);
};
std::string yesOrNo(bool val) {
return ((val==false) ? "Yes" : "No");
}
int main()
{
int drvIdx = 1;
std::bitset<64> bitsOfDrvAns{mDrvAns};
std::cout << bitsOfDrvAns << std::endl;
std::cout << "Has drv " << drvIdx << " answered? " << yesOrNo(getDrvAns(drvIdx))
<< std::endl;
drvIdx = 65;
std::cout << "Has drv " << drvIdx << " answered? " << yesOrNo(getDrvAns(drvIdx))
<< std::endl;
return 0;
}
| According to the documentation, out of bounds access using operator[] is Undefined Behaviour. Don't do it.
If you don't want to check the bounds yourself, call test() instead, and be prepared to handle the exception if necessary.
|
70,035,020 | 70,035,021 | Compiler variance in function template argument deduction | The following program:
#include <type_traits>
template<typename T, bool b>
struct S{
S() = default;
template<bool sfinae = true,
typename = std::enable_if_t<sfinae && !std::is_const<T>::value>>
operator S<T const, b>() { return S<T const, b>{}; }
};
template<typename T, bool b1, bool b2>
void f(S<const std::type_identity_t<T>, b1>,
// ^- T in non-deduced context for func-param #1
S<T, b2>)
// ^- T deduced from here
{}
int main() {
S<int, true> s1{};
S<int, false> s2{};
f(s1, s2);
}
is accepted by GCC (11.2) but rejected by Clang (13) and MSVC (19.latest), all for -std=c++20 / /std:c++20 (DEMO).
What compiler is correct here?
| This is governed by [temp.deduct.call], particularly /4:
In general, the deduction process attempts to find template argument values that will make the deduced A identical to A (after the type A is transformed as described above). However, there are three cases that allow a difference: [...]
In the OP's example, A is S<const int, true> and the (transformed) A is S<int, int>, and none of these [three] cases applies here, meaning deduction fails.
We may experiment with this by tweaking the program such that the deduced A vs tranformed A difference falls under one of the three cases; say [temp.deduct.call]/4.3
If P is a class and P has the form simple-template-id, then the transformed A can be a derived class D of the deduced A. [...]
#include <type_traits>
template<typename T, bool b>
struct S : S<const T, b> {};
template<typename T, bool b>
struct S<const T, b> {};
template<typename T, bool b1, bool b2>
void f(S<const std::type_identity_t<T>, b1>, S<T, b2>){}
int main() {
S<int, true> s1{};
S<int, true> s2{};
f(s1, s2);
}
This program is correctly accepted by all three compilers (DEMO).
Thus, GCC most likely has a bug here, as the error argued for above is diagnosable (not ill-formed NDR). As I could not find an open bug for the issues, I've filed:
Bug 103333 - [accepts-invalid] function template argument deduction for incompatible 'transformed A' / 'deduced A' pair
We may also note that [temp.arg.explicit]/7 contains a special case where implicit conversions are allowed to convert an argument type to the function parameter type:
Implicit conversions ([conv]) will be performed on a function argument to convert it to the type of the corresponding function parameter if the parameter type contains no template-parameters that participate in template argument deduction.
This does not apply in OP's example, though, as the (function) parameter type S<const std::type_identity_t<T>, b1> contains also the (non-type) template parameter b1, which participates in template argument deduction.
However in the following program:
#include <type_traits>
template<typename T>
struct S{
S() = default;
template<bool sfinae = true,
typename = std::enable_if_t<sfinae && !std::is_const<T>::value>>
operator S<T const>() { return S<T const>{}; }
};
template<typename T>
void f(S<const std::type_identity_t<T>>, S<T>) {}
int main() {
S<int> s1{};
S<int> s2{};
f(s1, s2);
}
the (function) parameter type is A<std::type_identity_t<T>>, and the only template parameter in it is T which does not participate in template argument deduction for that parameter-argument pair (P/A). Thus, [temp.arg.explicit]/7 do apply here and the program is well-formed.
|
70,035,099 | 70,035,957 | How to extract requires clause with a parameter pack whose parameters are related to each other into a concept? | I've got such a set of toy functions:
template <typename... Args>
requires std::conjunction_v<std::is_convertible<Args, int>...>
void test(Args...) { std::cout << "int"; }
template <typename... Args>
requires std::conjunction_v<
std::disjunction<std::is_convertible<Args, int>,
std::is_convertible<Args, std::string>>...> &&
std::disjunction_v<std::is_convertible<Args, std::string>...>
void test(Args...) { std::cout << "istring"; }
The first function will be called when I uses arguments that are all convertible to int and unconvertible to std::string, like: test(1, 2L, 3.0, 4UL).
If there's at least one argument that is convertible to std::string and if all arguments are either convertible to int or std::string, the second function will be called, like test(1, 2L, "Hello", 4UL).
And it does as I expected.
However, when I code the second function as the below two style, it doesn't work. The concept of arguments are checked one after another, and 1, 2L, 4UL are not a Istring.
template <typename... Args>
concept Istring = std::conjunction_v<
std::disjunction<std::is_convertible<Args, int>,
std::is_convertible<Args, std::string>>...> &&
std::disjunction_v<std::is_convertible<Args, std::string>...>;
void test(Istring auto...) { std::cout << "istring"; }
template <typename... Args>
concept Istring = std::conjunction_v<
std::disjunction<std::is_convertible<Args, int>,
std::is_convertible<Args, std::string>>...> &&
std::disjunction_v<std::is_convertible<Args, std::string>...>;
template <IString... Args>
void test(Args...) { std::cout << "istring"; }
I'm wondering whether there's a way to extract the concept.
| There is no need to use std::conjunction and std::disjunction in such a case since it makes the code verbose and difficult to read. Using fold expressions will be more intuitive.
template <typename... Args>
requires (std::is_convertible_v<Args, int> && ...)
void test(Args...) { std::cout << "int\n"; }
template <typename... Args>
concept Istring =
((std::is_convertible_v<Args, int> ||
std::is_convertible_v<Args, std::string>) && ...) &&
(std::is_convertible_v<Args, std::string> || ... );
template <Istring... Args>
void test(Args...) { std::cout << "istring\n"; }
In the above example, Istring will only constrain a single parameter instead of the parameter pack, that is, check whether each parameter satisfies the following degenerate constraint:
template <typename T>
concept Istring =
(std::is_convertible_v<T, int> || std::is_convertible_v<T, std::string>) &&
std::is_convertible_v<T, std::string>;
You should use the requires clause to check all parameters, for example:
template <typename... Args>
requires Istring<Args...>
void test(Args...) { std::cout << "istring\n"; }
Demo.
|
70,035,653 | 70,035,812 | c++ return two arrays from the function | I find a solution to the equation using the bisection method.
And I need to find the value of a and b on some iterations. Therefore, I made two arrays for these points, respectively.
in order to "pull out" the number of iterations from the function, I had no problems. They are displayed on the screen. But how do I "pull out" these two arrays?Please tell me how to do it. Thank you in advance!
double f1(double x){
return x*x-5*sin(x);
}
double f2(double x){
return exp(x)-pow(10,x);
}
double f3(double x){
return sin(x)-x+0.15;
}
double f4(double x){
return x-pow(9+x,0.5)+x*x-4;
}
double dihotom (double a , double b , double e , double(*fp)(double),int &iter,double &points_a[],double &points_b[]){
double c , fc , fa = fp(a);
iter=(log10((b-a)/e))/log10(2);
int step = iter/3;
int step_current = step;
int it=0;
int k=0;
do{
c=(a+b)/2;
fc=fp(c);
if (fa*fc<=0) b = c ; else a = c;
it++;
if(it==step_current){
points_a[k]=a;
points_b[k]=b;
k++;
step_current=step_current+step;
}
fa=fp(a);
printf ("it %d: a = %lf,b = %lf\n",iter,a,b);
}while (fabs(a-b)>=e);
return c;
}
int main(int argc, char *argv[]) {
int int_s=0;
double points_a[3];
double points_b[3];
double k3= dihotom (0.5,1,0.0001,f3,int_s,points_a[3],points_b[3]);
printf("For F3 - root = %lf, F3(%.2lf)=%lf ;iter =%d\n", k3, k3 ,f3(k3),int_s);
int i=0;
for(i=0;i<3;i++){
printf("step : %d , a: %lf, b: %lf ", i,points_a[i],points_b[i]);
}
return 0;
}
| In your case, you should take the arrays by reference:
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double (&points_a)[3], double (&points_b)[3]) {
// ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
You could also let the arrays decay into pointers:
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double points_a[], double points_b[]) {
or
double dihotom(double a, double b, double e, double (*fp)(double), int &iter,
double* points_a, double* points_b) {
But by taking them by reference, you make sure that you only accept arrays of the correct size.
In either case, the call to the function will simply be:
double k3 = dihotom(0.5, 1, 0.0001, f3, int_s, points_a, points_b);
Demo
|
70,035,959 | 70,036,183 | How can I create an instance from a UObject class? | I have a DataTable with a list of items that can be dropped by enemies, along with their rarities and min/max quantities:
USTRUCT(BlueprintType)
struct FItemDropRow : public FTableRowBase
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, BlueprintReadOnly)
TSubclassOf<UBattleItemBase> DropItemClass;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
EItemRarity RarityTier;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
int MinDrop;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
int MaxDrop;
};
And here's the function on the character where the drops are selected:
// Pick a random entry from a list of items filtered by rarity
int SelectedIndex = FMath::RandRange(0, UsableRowIndexArray.Num() - 1);
// Retrieve that entry from the DataTable
FItemDropRow* SelectedRow = ItemDropDataTable->FindRow<FItemDropRow>(
UsableRowIndexArray[SelectedIndex],
ContextString
);
// Pick a random amount to drop from the min/max defined on the DataTable row
int DropQuantity = FMath::RandRange(
SelectedRow->MinDrop,
SelectedRow->MaxDrop
);
// Initialize the array with the item instance and the quantity to add
TArray<UBattleItemBase*> ItemsToReturn;
ItemsToReturn.Init(SelectedRow->DropItemClass, DropQuantity);
return ItemsToReturn;
The issue is that the DataTable is only storing references to the classes:
C2664 'void TArray::Init(UBattleItemBase *const &,int)':
cannot convert argument 1 from 'TSubclassOf' to 'UBattleItemBase *const &'
But I need it as an instance so I can add it to the player's inventory and modify it's quantity. I've tried the Instanced flag in the FItemDropRow struct, but that causes the DropItemClass to no longer appear as an editable property in the DataTable
| DropItemClass is only the class of the item, not an instance of it.
If you want to create an instance from that class you can use NewObject() or one of the more advanced versions (NewNamedObject() / ConstructObject(), CreateObject(), etc...)
e.g.:
TArray<UBattleItemBase*> ItemsToReturn;
for(int i = 0; i < DropQuantity; i++)
ItemsToReturn.Add(NewObject<UBattleItemBase>(
(UObject*)GetTransientPackage(),
SelectedRow->DropItemClass
));
this would create DropQuantity instances of the specified DropItemClass.
The first parameter to NewObject() will be the outer for the newly created object, so if you want it to be owned by any object you should pass that one instead.
|
70,036,511 | 70,037,021 | How to delete column in 2d array c++ with dynamic array? | I want to delete column with max integer in 2d array, I do it in this way, but why is deleting the column and also row? Can I fix that and delete only column? The task was do it with delete command, but now I think it's impossible
#include <iostream>
using namespace std;
int main()
{
int row = 3, col = 3;
int** arr = new int* [row];
for(int i = 0; i < row; i++){
arr[i] = new int[col];
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++) {
cin >> arr[i][j];
}
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
cout << " ------------- " << endl;
int max = 0, index = 0;
for(int i =0; i < row; i++){
for(int j = 0; j < col; j++){
if(arr[i][j] > max){
max = arr[i][j];
index = i;
}
}
}
delete [] arr[index];
int** tmp = new int*[index - 1];
int tmpI = 0;
for(int i = 0; i < col; i++){
if(i != index){
tmp[tmpI++] = arr[i];
}
}
delete [] arr;
arr = tmp;
col = col - 1;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
| For starters the variable index is set to a row number
index = i;
Then this row is deleted
delete [] arr[index];
But you are going to remove a column instead of a row. So this code does not make a sense.
Also you are incorrectly searching the maximum element. If the user will enter all negative values then the maximum value will be equal to 0 though an element with such value is not present in the array.
In this declaration
int** tmp = new int*[index - 1];
you allocated an array with rows that one less than the number of rows in the original array. Moreover if index is equal to 0 then there is allocated a very large extent of memory.
This statement
delete [] arr;
produces a memory leak.
It seems what you need is something like the following
#include <iostream>
int main()
{
size_t row = 3, col = 3;
int **arr = new int * [row];
for ( size_t i = 0; i < row; i++ )
{
arr[i] = new int[col];
}
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
std::cin >> arr[i][j];
}
}
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << "------------- " << std::endl;
size_t max_i = 0, max_j = 0;
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
if ( arr[max_i][max_j] < arr[i][j] )
{
max_i = i; max_j = j;
}
}
}
int **tmp = new int*[row];
for ( size_t i = 0; i < row; i++ )
{
tmp[i] = new int[col-1];
}
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0, k = 0; j < col; j++ )
{
if ( j != max_j ) tmp[i][k++] = arr[i][j];
}
}
for ( size_t i = 0; i < row; i++ )
{
delete [] arr[i];
}
delete [] arr;
arr = tmp;
--col;
for ( size_t i = 0; i < row; i++ )
{
for ( size_t j = 0; j < col; j++ )
{
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
for ( size_t i = 0; i < row; i++ )
{
delete [] arr[i];
}
delete [] arr;
return 0;
}
The program output might look like
1 2 3
6 5 4
7 9 8
-------------
1 3
6 4
7 8
|
70,037,105 | 70,038,230 | Get byte representation of C++ class | I have objects that I need to hash with SHA256. The object has several fields as follows:
class Foo {
// some methods
protected:
std::array<32,int> x;
char y[32];
long z;
}
Is there a way I can directly access the bytes representing the 3 member variables in memory as I would a struct ? These hashes need to be computed as quickly as possible so I want to avoid malloc'ing a new set of bytes and copying to a heap allocated array. Or is the answer to simply embed a struct within the class?
It is critical that I get the exact binary representation of these variables so that the SHA256 comes out exactly the same given that the 3 variables are equal (so I can't have any extra padding bytes etc included going into the hash function)
| Most Hash classes are able to take multiple regions before returning the hash, e.g. as in:
class Hash {
public:
void update(const void *data, size_t size) = 0;
std::vector<uint8_t> digest() = 0;
}
So your hash method could look like this:
std::vector<uint8_t> Foo::hash(Hash *hash) const {
hash->update(&x, sizeof(x));
hash->update(&y, sizeof(y));
hash->update(&z, sizeof(z));
return hash->digest();
}
|
70,037,239 | 70,037,294 | unusual switch statement label - why isn't this a syntax error? | I've inherited a very old (+15 years old) C++ program currently running on AIX using IBM's xlc compiler. I came across a switch statement and I don't understand how this ever worked.
Below is a minimal example that shows the situation.
#include <iostream>
using namespace std;
int main()
{
int i=5;
switch( i ) {
case 1:
cout << "case " << i << endl;
break;
case 2:
cout << "case " << i << endl;
break;
Otherwise:
cout << "case " << i << endl;
break;
}
cout << "bye\n";
}
I'm using GCC 7.3.1 on Amazon Linux 2. The program compiles fine and shows this output is:
bye
If I add "-Wall", then it tells me the following:
minex.C: In function ‘int main()’:
minex.C:15:3: warning: label ‘Otherwise’ defined but not used [-Wunused-label]
Otherwise:
^~~~~~~~~
Questions:
Why isn't this a syntax error?
Don't the case labels have to follow the form "case n:" where n is
an integer expression or "default:" (or a constant String expression, but that doesn't seem relevant here?
Can someone please point me to a reference that says this is
supposed to be allowed?
| A label can occur on any statement. That the statement happens to be inside of a switch block doesn't matter. This label can be jumped to from anyplace inside the current function.
A case label or default can only appear inside of a switch, but that doesn't prevent other labels from appearing there as well.
Section 9.1 of the C++17 standard describes labeled statements:
1 A statement can be labeled.
labeled-statement:
attribute-specifier-seqopt identifier : statement
attribute-specifier-seqopt case constant-expression :
statement
attribute-specifier-seqopt default : statement
The optional attribute-specifier-seq appertains to the label. An
identifier label declares the identifier. The only use of an
identifier label is as the target of a goto. The scope of a label is
the function in which it appears. Labels shall not be redeclared
within a function. A label can be used in a goto statement before
its declaration. Labels have their own name space and do not interfere
with other identifiers. [ Note: A label may have the same name as
another declaration in the same scope or a template-parameter from an
enclosing scope. Unqualified name lookup (6.4.1) ignores labels. — end
note ]
2 Case labels and default labels shall occur only in switch statements
Note that there are restrictions on case and default but not other labels.
|
70,037,430 | 70,263,559 | Qt: How to implement Panning/Zooming in QGraphicsScene with two finger gestures on laptop trackpad (win/mac)? | I have a Qt 6.2 Application (Windows/Mac) using QGraphicsScene and want to use 2 fingers on the touch pad of my laptop for panning - as many other applications do.
Zooming in/out works fine, but using 2 fingers for panning always results in zoom out.
I found a number of questions and some fragmentary samples. But no half way complete example:
Finger Scrolling in QGraphicsView in QT?
https://forum.qt.io/topic/119221/how-to-listen-to-qtouchevent-originating-from-a-precision-touch-pad
https://doc.qt.io/qt-5/gestures-overview.html
What is the right way to do this?
What i tried so far (on Windows):
1)
MyGraphicsView::MyGraphicsView(...) : QGraphicsView()
{
viewport()->setAttribute(Qt::WA_AcceptTouchEvents);
...
bool MyGraphicsView::viewportEvent ( QEvent * event )
{
switch (event->type())
{
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
{
// never called
}
MyDocWin::MyDocWin(...) : CMDIAppDocWin(),
{
setAttribute(Qt::WA_AcceptTouchEvents);
...
bool MyDocWin::event(QEvent *event)
{
switch (event->type())
{
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
{
// never called
}
...
std::vector<Qt::GestureType> sgGestureTypes = {Qt::TapGesture, Qt::TapAndHoldGesture,Qt::PanGesture ,Qt::PinchGesture ,Qt::SwipeGesture };
MyGraphicsView::MyGraphicsView(...) : QGraphicsView()
{
for(Qt::GestureType gesture : sgGestureTypes)
grabGesture(gesture);
...
bool MyGraphicsView::event(QEvent *event)
{
switch (event->type())
{
case QEvent::Gesture:
case QEvent::NativeGesture:
// never called
MyDocWin::MyDocWin(...) : CMDIAppDocWin(),
{
for (Qt::GestureType gesture : sgGestureTypes)
grabGesture(gesture);
...
bool MyDocWin::event(QEvent *event)
{
switch (event->type())
{
case QEvent::Gesture:
case QEvent::NativeGesture:
// never called
| I finally manged to get this work. What i found out:
Pan Gestures (in Qt) are converted to Mouse Wheel messages which can have a y and also a x offset. This seems strange to me, as there is no Mouse with a horizontal Wheel.
Even more confusing, by MS definition Pan events are converted to WM_VSCROLL/WM_HSCROLL events (https://learn.microsoft.com/en-us/windows/win32/wintouch/windows-touch-gestures-overview)
Most of this (i.e panning) is handled quite well by Qt, but not all:
It seems impossible to distinguish between a gesture event on the track pad and a real wheel event on the mouse. I originally wanted to use the Mouse Wheel always for Zoom AND use the Touch Pads Pan gesture. This combination seems to be impossible. I now use Ctrl/Shift for mouse wheel zoom. This solved the problem
The zoom gesture with two fingers i had to handle differently on Mac and Windows:
On windows a wheel event is sent with “(event->modifiers() & Qt::ControlModifier) == true”. On the mac not. So i wrote:
void myGraphicsView::wheelEvent(QWheelEvent* event)
{
if(event->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier))
myZoomFunction(event, 0);
else
QGraphicsView::wheelEvent(event);
}
On MacOs we have to listen to a QEvent::NativeGesture - but thats not called on Windows:
bool myGraphicsView::viewportEvent ( QEvent * event )
{
switch (event->type())
{
case QEvent::NativeGesture:
auto nge = dynamic_cast<QNativeGestureEvent*>(event);
if (nge)
{
if(nge->gestureType() == Qt::ZoomNativeGesture)
On MacOs scrolling up/down is sent in angleDelta().x(), instead of angleDelta().y(). Both values are swapped for any reason.
|
70,037,538 | 70,037,831 | Using template function for accessing the raw bytes of POD data type and strings | I'm trying to make a function template that lets me process the raw bytes of a POD data type and strings.
I came up with this somewhat naive approach (I'm not using template a lot, and I'm able to write them use them only for very simple cases):
#include <cstdio>
template<typename T>
void PrintBytes(T object)
{
unsigned char* p = reinterpret_cast<unsigned char*>(&object);
for (int i = 0; i < sizeof object; i++)
{
printf("%02x ", *p++);
}
printf("\n");
}
int main()
{
int a = 10;
PrintBytes(a); // works as expected
short b = 12;
PrintBytes(b); // works as expected
const char* foo = "ABC";
PrintBytes(foo); // works as expected, but doesn't do what I want
const char bar[] = "ABC";
PrintBytes(bar); // works as expected, but doesn't do what I want
}
Output
0a 00 00 00
0c 00
a4 ac 5b 8c f6 7f 00 00
a4 fb 7f 07 b7 00 00 00
Desired output for the last two cases
41 42 43
41 42 43
Obviously the first two cases work and the last two cases don't because foo and bar are already pointers and the unsigned char* p = reinterpret_cast<unsigned char*>(&object) should rather be unsigned char* p = object and the sizeof object should be strlen(object).
How can this be done with C++ templates? I can use c++17.
| You can use C++17 if constexpr to perform the corresponding address and size method according to the type of T, something like this:
#include <cstdio>
#include <cstring>
#include <utility>
#include <type_traits>
template<typename T>
void PrintBytes(T object)
{
auto [p, size] = [&] {
if constexpr (std::is_same_v<T, const char*>)
return std::pair{object, strlen(object)};
else
return std::pair{reinterpret_cast<unsigned char*>(&object), sizeof(object)};
}();
for (int i = 0; i < size; i++)
{
printf("%02x ", *p++);
}
printf("\n");
}
Demo.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.