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,542,993 | 70,543,751 | Why does the thread sanitizer complain about acquire/release thread fences? | I'm learning about different memory orders.
I have this code, which works and passes GCC's and Clang's thread sanitizers:
#include <atomic>
#include <iostream>
#include <future>
int state = 0;
std::atomic_int a = 0;
void foo(int from, int to)
{
for (int i = 0; i < 10; i++)
{
while (a.load(std::memory_order_acquire) != from) {}
state++;
a.store(to, std::memory_order_release);
}
}
int main()
{
auto x = std::async(std::launch::async, foo, 0, 1);
auto y = std::async(std::launch::async, foo, 1, 0);
}
I reckon that an 'acquire' load is unnecessary if it doesn't end up returning from, so I decided to use a 'relaxed' load, followed by an 'acquire' fence.
I expected it to work, but it's rejected by the thread sanitizers, which claim that concurrent state++s are a data race.
#include <atomic>
#include <iostream>
#include <future>
int state = 0;
std::atomic_int a = 0;
void foo(int from, int to)
{
for (int i = 0; i < 10; i++)
{
while (a.load(std::memory_order_relaxed) != from) {}
std::atomic_thread_fence(std::memory_order_acquire);
state++;
a.store(to, std::memory_order_release);
}
}
int main()
{
auto x = std::async(std::launch::async, foo, 0, 1);
auto y = std::async(std::launch::async, foo, 1, 0);
}
Why is this a data race?
Cppreference says that
Atomic-fence synchronization
An atomic release operation X in thread A synchronizes-with an acquire
fence F in thread B, if
there exists an atomic read Y (with any memory order)
Y reads the value written by X (or by the release sequence headed by X)
Y is sequenced-before F in thread B
In this case, all non-atomic and relaxed atomic stores that are
sequenced-before X in thread A will happen-before all non-atomic and
relaxed atomic loads from the same locations made in thread B after F.
In my understanding, all conditions are met:
"there exists an atomic read Y (with any memory order)" — check: a.load(std::memory_order_relaxed).
"Y reads the value written by X" — check, it reads the value from a.store(to, std::memory_order_release);.
"Y is sequenced-before F in thread B" — check.
| The thread sanitizer currently doesn't support std::atomic_thread_fence. (GCC and Clang use the same thread sanitizer, so it applies to both.)
GCC 12 (currently trunk) warns about it:
atomic_base.h:133:26: warning: 'atomic_thread_fence' is not supported with '-fsanitize=thread' [-Wtsan]
133 | { __atomic_thread_fence(int(__m)); }
| ~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~
To stop the sanitizer from disregarding fences, you can manually instrument them, using __tsan_acquire and __tsan_release.
#include <sanitizer/tsan_interface.h>
while (a.load(std::memory_order_relaxed) != from) {}
__tsan_acquire(&a); // <--
std::atomic_thread_fence(std::memory_order_acquire);
I assume it's tricky to automatically determine which atomic variables are affected by the fence.
Even though the bug report says seq_cst fences are not affected, the code is still rejected if I use such a fence, they still need to be annotated with __tsan_acquire+__tsan_release, exactly the same as acq-rel fences.
|
70,543,041 | 70,545,421 | Address of variable supplied instead of its value | I wan testing an example of fopen and fclose in C++ where the code reads the integer values in thee file but if the file is empty (no integers), the value retrieved is not 0 but -858993460. i think this is the address of the variable in fscanf() but how could i get the null or /0 value
the following code is problematic
#include <stdio.h>
int main()
{
{
int a, sum = 0 ,num, n = 0;
FILE* pFile;
pFile = fopen("input.txt", "r");
fscanf(pFile, "%d", &num);
while (n != 5) {
n = n + 1;
sum = sum + num;
fscanf(pFile, "%d", &num);
}
fclose(pFile);
printf("I have read: %d numbers and sum is %d \n", n, sum);
scanf("Hi %d", &a);
return 0;
}
}
input.txt : (empty) or :
12 32 43 56 78
NOTE: the code is problematic because num is never read as 0 so the loop keeps going on.
I will add further details on the problem: if the input file contains five integers:
12 32 43 56 78
and the code goes as follows:
#include <stdio.h>
int main()
{
{
char str[80];
int a, sum = 0 ,num, n = 0;
FILE* pFile;
pFile = fopen("input.txt", "r");
fscanf(pFile, "%d", &num);
while (n != 5) {
n = n + 1;
sum = sum + num;
fscanf(pFile, "%d", &num);
}
fclose(pFile);
printf("I have read: %d numbers and sum is %d \n", n, sum);
scanf("Hi %d", &a);
return 0;
}
}
output:
I have read: 5 numbers and sum is 221
| The fix is simple, never miss returned values of IO functions.
FILE* pFile;
// pFile = fopen("input.txt", "r");
// fscanf(pFile, "%d", &num);
// while (n != 5) {
if ((pFile = fopen("input.txt", "r")) == NULL) // If unable to open file
return 1;
while (n != 5 && fscanf(pFile, "%d", &num) == 1) { // And if num is successfully assigned
n = n + 1;
sum = sum + num;
// Odd: fscanf(pFile, "%d", &num);
}
fclose(pFile);
|
70,543,372 | 70,543,641 | How to cast from const void* in a constexpr expression? | I'm trying to reimplement memchr as constexpr (1). I haven't expected issues as I have already successfully done the same thing with strchr which is very simmilar.
However both clang and gcc refuse to cast const void* to anything else within constexpr function, which prevents me to access the actual values.
I understand that working with void* in constexpr function is weird, as we cannot do malloc and there is no way to specify arbitrary data as literal values. I'm doing this basically as a part of an excercise to rewrite as much as I can from as constexpr (2).
Still I'd like to know why this is not allowed and if there is any way around it.
Thank you!
(1) My implementation of memchr:
constexpr void const *memchr(const void *ptr, int ch, size_t count) {
const auto block_address = static_cast<const uint8_t *>(ptr);
const auto needle = static_cast<uint8_t>(ch);
for (uintptr_t pos{0}; pos < count; ++pos) {
auto byte_address = block_address + pos;
const uint8_t value = *byte_address;
if (needle == value) {
return static_cast<void const *>(byte_address);
}
}
return nullptr;
}
(2) The entire project on Github: https://github.com/jlanik/constexprstring
| No, it is impossible to use void* in such a way in constant expressions. Casts from void* to other object pointer types are forbidden in constant expressions. reinterpret_cast is forbidden as well.
This is probably intentional to make it impossible to access the object representation at compile-time.
You cannot have a memchr with its usual signature at compile-time.
The best that I think you can do is write the function for pointers to char and its cv-qualified versions, as well as std::byte (either as overloads or as template), instead of void*.
For pointers to objects of other types it is going to be tricky in some cases and impossible in most cases to implement the exact semantics of memchr.
While I am not certain that it is possible, maybe, in a templated version of memchr, one can read the underlying bytes of the objects passed-by-pointer via a std::bit_cast into a struct containing a std::byte/unsigned char array of appropriate size.
|
70,543,449 | 70,543,537 | How to use std::acumulate for matrix | #include <iostream>
#include <numeric>
#include <vector>
using matrix = std::vector<std::vector<int>>;
int main()
{
matrix mtx{5, std::vector<int>(5)};
int sum = 0;
for (const auto i : mtx) // can be avoided ?
sum += std::accumulate(i.begin(), i.end(), 0,
[](int a, int b){a > 0 ? a + b : a;});
}
I want to use std::accumulate for std::vector<std::vector<int>> but I am curious if I can avoid the loop. Also I want to know if the last argument is ok.
| Based on your lambda, looks like you want to just sum the positive entries:
#include <iostream>
#include <numeric>
#include <vector>
using Number = int;
using Matrix = std::vector<std::vector<Number>>;
int main() {
Matrix mtx{5, std::vector<Number>(5, 1)};
Number sum_positives = std::accumulate(
mtx.begin(), mtx.end(), Number(0), [](Number const acc, auto const &v) {
return std::accumulate(
v.begin(), v.end(), acc,
[](Number const a, Number const b) { return b > 0 ? a + b : a; });
});
std::cout << sum_positives << std::endl; // 25
return 0;
}
Don't forget that the lambda you pass to std::accumulate() must return a value.
|
70,543,626 | 70,544,325 | Program freezing if function is present after the freezing point | When function analiza() isn't commented, my program shows both messages in input() function. (przed, po), But, if I uncomment the analiza() after input(), it breaks. I tried cleaning buffers, diffrent libraries ect. NOTHING helped. Code:
#include <iostream>
using namespace std;
unsigned int liczba_osob, liczba_klapek, przeszli = 0;
unsigned long long osoby[200000], klapki[200000], minimum;
bool do_uzycia[200000]{0};
unsigned long long greatest();
bool czy_mozliwe(unsigned int osoba);
void input();
void analiza();
int main()
{
input();
analiza();
return 0;
}
unsigned long long greatest()
{
unsigned long long maxrn = klapki[0];
for (unsigned int i = 1; i < liczba_klapek; i++)
if (klapki[i] > maxrn)
maxrn = klapki[i];
return maxrn;
}
bool czy_mozliwe(unsigned int osoba)
{
if (osoby[osoba] >= minimum)
return 1;
unsigned long long maximim = greatest();
if (osoby[osoba] + maximim < minimum)
return 0;
for (unsigned int i = 0; i < liczba_klapek; i++)
{
if (osoby[osoba] + klapki[i] >= minimum && !do_uzycia[i])
{
do_uzycia[i] = 1;
return 1;
}
}
return 0;
}
void input()
{
cin >> liczba_osob;
for (unsigned int i = 0; i < liczba_osob; i++)
cin >> osoby[i];
cin >> liczba_klapek;
for (unsigned int i = 0; i < liczba_klapek; i++)
cin >> klapki[i];
cout<<"przed";
cin >> minimum;
cout<<"po";
}
void analiza()
{
for (unsigned int i = 0; i < liczba_osob; i++)
if (czy_mozliwe(i))
przeszli++;
cout << przeszli;
}
So, the problem rn is with input:
200000
10 20 30... (and 199997 times more)
200000
10 20 30... (and 199997 more)
2500000
so max input due to arrays being 200000 long. Program freezes in the input() after cout<<"przed";. It doesn't get input to the minimum variable. If I remove call to analiza() in int main(), the problem doesn't occurr.
Here's the input file that makes the problem file
| For the given input, your function analiza makes 200000 = 2 * 10^5 calls to the function czy_mozliwe. That function in turn calls greatest, which makes 2 * 10^5 iterations of a loop with a comparison in each iteration, and then czy_mozliwe proceeds to run its own loop with 2 * 10^5 iterations.
So in order to finish executing analiza, the computer needs to execute 4 * 10^10 iterations of the loop in greatest and 4 * 10^10 iterations of the loop in czy_mozliwe.
That might take a long time.
Meanwhile the output you queued up with cout<<"po"; may just be waiting in a buffer. You haven't seen it come out because you didn't flush the buffer when you wrote it.
Try cout<<"po"<<std::endl; instead.
Then you might think about how you can write your program so it doesn't require so many iterations of its inner loops.
|
70,543,672 | 70,543,700 | Allowing access to protected member function for class outside of namespace | Consider the following code:
namespace A
{
class B
{
protected:
friend class C;
static void foo();
};
}
class C
{
public:
C() { A::B::foo(); }
};
int main()
{
C c;
return 0;
}
As currently constructed, this code will not compile - the friendship declared in class B applies to a (currently non-existent) A::C, and not the C in the global namespace. How can I work around this effectively, assuming I cannot add C to non-global namespace? I have tried using friend class ::C;, but the compiler does not like that. I have also tried forward declaring class C; before the namespace A scope, but that does not appear to work either.
| Adding a forward declaration for class C worked for me, what compiler are you using?
class C;
namespace A
{
class B
{
protected:
friend class ::C;
static void foo();
};
}
// ...
Live demo
Edit: as Vlad points out, both friend C and friend ::C also work, provided you have that forward declaration in place. But friend class C doesn't, I'll pass that one over to the language lawyers.
|
70,543,980 | 70,544,218 | Finding if a class template can be instantiated with a set of arguments, arity-wise (in C++17) | I have a template that takes a template template parameter and a pack of type arguments. I want to instantiate the template with the arguments only if the arities match. Something like this:
// can_apply_t = ???
template<template<typename...> typename Template, typename... Args>
struct test {
using type = std::conditional_t<can_apply_t<Template, Args...>, Template<Args...>, void>;
};
template<typename> struct unary_template;
template<typename, typename> struct binary_template;
static_assert(std::is_same_v< test<unary_template, int>::type, unary_template<int> >);
static_assert(std::is_same_v< test<binary_template, int>::type, void >);
I fantasized that it would be as simple as this:
template<template<typename... T> typename Template, typename... Args>
struct test {
using type = std::conditional_t<sizeof...(T) == sizeof...(Args), Template<Args...>, void>;
};
...but clang++12 says:
error: 'T' does not refer to the name of a parameter pack
|
fantasized that it would be as simple as this:
No... not as simple... when you write
using type = std::conditional_t<can_apply_t<Template, Args...>,
Template<Args...>,
void>;
the Template<Args...> must be an acceptable type also when test of conditional_t is false.
You need a can_apply_t that directly return Template<Args...> when possible, void otherwise.
I propose something as the following
template <template <typename...> class C, typename... Ts>
auto can_apply_f (int)
-> std::remove_reference_t<decltype(std::declval<C<Ts...>>())>;
template <template <typename...> class C, typename... Ts>
auto can_apply_f (long) -> void;
template <template <typename...> class C, typename ... Ts>
using can_apply_t = decltype(can_apply_f<C, Ts...>(0));
template <template<typename...> typename Template, typename... Args>
struct test {
using type = can_apply_t<Template, Args...>;
};
|
70,544,353 | 70,544,509 | How to make online compilers to ignore debug statements in C++? | I am using these lines of code for debugging my C++ program.
void dbg_out(){cerr << endl;}
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
But the problem with this is that when I am using dbg function and submit on an online judge like codeforces or codechef it is increasing execution of code. Is there a way to make the online compiler to ignore the debug statements ?
| You can make the preprocessor conditionally define the macro:
#ifdef DEBUG_LOG
#define dbg(...) std::cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
Now if you compile with the option -DDEBUG_LOG, the log would be sent to std::cerr. An online judge wouldn't add that command line option, but you can locally.
|
70,545,403 | 70,545,514 | Libcurl - curl_multi_wakeup | Reading the function description curl_multi_wakeup: enter link description here
Calling this function only guarantees to wake up the current (or the
next if there is no current) curl_multi_poll call, which means it is
possible that multiple calls to this function will wake up the same
waiting operation.
I am confused by the phrase - "the same waiting operation". How's that?
That is, suppose I have a function curl_multi_poll() in event standby mode in thread "A".
Now, for example, I call the curl_multi_wakeup() function twice from thread "B" and thread "C".
And what happens judging by this phrase:
...function will wake up the same waiting operation.
It turns out that the function curl_multi_poll - wakes up only once ?
| curl_multi_wakeup is meant to be used with a pool of threads waiting on curl_multi_poll.
What the document says is that if you call curl_multi_wakeup repeatedly, it will possibly wake up only a single thread, not necessarily one thread for each call to curl_multi_wakeup.
|
70,545,636 | 70,545,666 | Is there a way to check if a platform supports an OpenGL function? | I want to load some textures using glTexStorageXX(), but also fall back to glTexImageXX() if that feature isn't available to the platform.
Is there a way to check if those functions are available on a platform? I think glew.h might try to load the GL_ARB_texture_storage extensions into the same function pointer if using OpenGL 3.3, but I'm not sure how to check if it succeeded. Is it as simple as checking the function pointer, or is it more complicated?
(Also, I'm making some guesses at how glew.h works that might be wrong, it might not use function pointers and this might not be a run-time check I can make? If so, would I just... need to compile executables for different versions of OpenGL?)
if (glTexStorage2D) {
// ... calls that assume all glTexStorageXX also exist,
// ... either as core functions or as ARB extensions
} else {
// ... calls that fallback to glTexImage2D() and such.
}
| You need to check if the OpenGL extension is supported. The number of extensions supported by the GL implementation can be called up with glGetIntegerv(GL_NUM_EXTENSIONS, ...).
The name of an extension can be queried with glGetStringi(GL_EXTENSIONS, ...).
Read the extensions into a std::set
#include <set>
#include <string>
GLint no_of_extensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &no_of_extensions);
std::set<std::string> ogl_extensions;
for (int i = 0; i < no_of_extensions; ++i)
ogl_extensions.insert((const char*)glGetStringi(GL_EXTENSIONS, i));
Check if an extension is supported:
bool texture_storage =
ogl_extensions.find("GL_ARB_texture_storage") != ogl_extensions.end();
glTexStorage2D is in core since OpenGL version 4.2. So if you've created at least an OpenGL 4.2 context, there's no need to look for the extension.
When an extension is supported, all of the features and functions specified in the extension specification are supported. (see GL_ARB_texture_storage)
GLEW makes this a little easier because it provides a Boolean state for each extension.
(see GLEW - Checking for Extensions) e.g.:
if (GLEW_ARB_texture_storage)
{
// [...]
}
|
70,545,944 | 70,546,154 | c++ coroutines final_suspend for promise_type | below is a snippet testing empty coroutine playing with promise_type
#include <iostream>
#include <coroutine>
#define DEBUG std::cout << __PRETTY_FUNCTION__ << std::endl
struct TaskSuspendAll {
// must be of this name
struct promise_type {
TaskSuspendAll get_return_object() noexcept {
return TaskSuspendAll{
std::coroutine_handle<promise_type>::from_promise(*this)
};
}
std::suspend_always initial_suspend() noexcept {
DEBUG;
return {};
}
std::suspend_always final_suspend() noexcept {
DEBUG;
return {};
}
void unhandled_exception() {}
void return_void() {
DEBUG;
}
};
std::coroutine_handle<promise_type> ch;
};
TaskSuspendAll TestSuspendAll() {
DEBUG;
co_return;
}
int main() {
std::cout << std::endl;
auto t = TestSuspendAll();
t.ch.resume();
//t.ch.resume()
//t.ch.destroy();
return 0;
}
running this I get
std::__n4861::suspend_always TaskSuspendAll::promise_type::initial_suspend()
TaskSuspendAll TestSuspendAll()
void TaskSuspendAll::promise_type::return_void()
std::__n4861::suspend_always TaskSuspendAll::promise_type::final_suspend()
My understanding is that co_await is applied to initial_suspend and final_suspend. When I call TestSuspendAll in the main function it will eventually call co_await promise.initial_suspend() and return to the caller given i have std::suspend_always awaitable. Then i resume the coroutine and the body gets executed. At some point, we will have co_await promise.final_suspend() and again return to the caller.
question: I would expect that i have to do a second call to resume coroutine so that co_await promise.final_suspend() succeeded and coroutine completed. However that causes seg fault. I know that it's undefined behavior calling resume on completed coroutine, however it's not completed 100% as far as I understand. My expectation was that final_suspend behaves the same as initial_suspend... what is the logic here? is that we have to use destroy after call to final_suspend?
thanks a lot for clarification!
VK
| Being suspended at its final suspend point is the definition of a coroutine being done. Literally; that's what coroutine_handle::done returns. Attempting to resume such a coroutine is UB.
So your expectation is not correct.
|
70,546,084 | 70,577,034 | How do I annotate seq-cst atomic fences for the thread sanitizer? | I learned that TSAN doesn't understand std::atomic_thread_fence, and to fix it, you need to tell TSAN which atomic variables are affected by the fence, by putting __tsan_acquire(void *) and __tsan_release(void *) next to it (for acquire and release fences respectively).
But what about seq-cst fences? As I understand, they're more strict than acq-rel fences, so acq-rel annotations might not be enough?
I'm not too familiar with different memory orders, so I might be missing something.
| @dvyukov on Github confirmed the __tsan_acquire+__tsan_release instrumentation (same as for acq-rel fences) should be enough.
I'm not sure if it means that TSAN doesn't distinguish between seq-cst and acq-rel operations in general, or not.
|
70,546,162 | 70,546,215 | Function to provide a default value when working with std::map | I am trying to write a function, which will give me a default value when the key is not inside a std::map. In all cases will my default value be numerical_limit::infinity().
Hovewer this simple example is not working.
#include <iostream>
#include <map>
#include <limits>
template<typename KeyType, typename ValueType>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const KeyType & key)
{
if(!map.contains(key))
{
return std::numeric_limits<ValueType>::infinity();
}
else
{
return map[key];
}
}
int main()
{
std::map<std::string, int> map;
auto el = mapDefaultInf(map, "alexey");
std::cout << el << std::endl;
return 0;
}
Error is:
main.cpp:29:42: error: no matching function for call to ‘mapDefaultInf(std::map, int>&, const char [7])’
Can someone help me understand the error.
Thanks in advance.
| First of all you use operator[] on the map object inside the function. That will never be allowed because it is a non-const function and you have passed the map by const reference. Instead you should rewrite the function implementation to use iterators:
template<typename KeyType, typename ValueType>
ValueType mapDefaultInf(const std::map<KeyType, ValueType> & map, const KeyType & key)
{
const auto it = map.find(key);
return it != map.end() ? it->second : std::numeric_limits<ValueType>::infinity();
}
Second of all you have an ambiguity in the key type. You need to pass in a std::string. Like this:
auto el = mapDefaultInf(map, std::string("alexey"));
|
70,546,204 | 70,546,230 | C++ how can I create an array of objects when there is a constructor? | If myClass does not have a constructor the following works fine:
myClass x[5];
If I put a constructor in myClass this line results in a compiling error.
What is standard practice for creating an array of objects when a constructor is defined?
Is it possible to populate the entire array of objects with a single constructor?
|
If myClass does not have a constructor the following works fine:
This is if your class has no user-declared constructor. In that case it has an implicitly-declared default constructor, which is what will be used by
myClass x[5];
to construct the objects.
If you declare a constructor yourself, the implicit default constructor will not be declared. Instead you can declare your own. A default constructor is just a constructor that can be called without arguments:
class myClass {
public:
myClass() {
// Default constructor
}
};
or, if you just want the default constructor to behave exactly as the implicit one would, you can default it:
class myClass {
public:
myClass() = default;
};
If you don't want to do that and use a different constructor, you may still be able to use list initialization:
myClass x[5] = {{/*constructor arguments for first object*/},
{/*constructor arguments for second object*/},
//...
};
Or, easier, just use std::vector<myClass> and push_back or emplace_back each element with the constructor arguments that you need.
std::vector<myClass> x;
x.emplace_back(/*constructor arguments for first object*/);
x.emplace_back(/*constructor arguments for second object*/);
//...
which can also be done in a loop, or, if all all objects are supposed to be copies of one another:
std::vector<myClass> x(5, myClass(/*constructor arguments*/));
|
70,546,540 | 70,546,569 | Infinite loop created when inputting "yy" into a char variable that should only take a single character such as 'y' or 'n', "nn" does not break code | The code in the cont function asks the user if they want to play my game again.
The code works when receiving proper character inputs such as 'y' or 'n' as well as their respective capital letter variants, and the else block works properly to loop the function if an invalid input such as 'a' or 'c' is entered.
However during a test run, an input of 'yy' breaks the code causing the program to infinitely loop, running not only this cont function but my game function as well.
choice is stored as a char variable. I am wondering why the code even continues to run upon inputting multi-character inputs such as 'yy' or 'yes'. What's interesting is 'nn', 'ny' and other variations of multi-character inputs that begin with 'n' causes no issues and properly results in the else if block running as intended. Which prints "Thanks for playing." then ends the program.
Can variables declared as char accept inputs greater than 1 character? Does it only take the first value? And if so why does 'yy' cause a loop rather than the program running as intended by accepting a value of 'y' or 'Y'? How can I change my program so that an input of 'yy' no longer causes issues, without specific lines targeting inputs such as 'yy' or 'yes'.
#include <iostream>
#include <string> // needed to use strings
#include <cstdlib> // needed to use random numbers
#include <ctime>
using namespace std;
// declaring functions
void cont();
void game();
void diceRoll();
// variable declaration
string playerName;
int balance; // stores player's balance
int bettingAmount; // amount being bet, input by player
int guess; // users input for guess
int dice; // stores the random number
char choice;
// main functions
int main()
{
srand(time(0)); // seeds the random number, generates random number
cout << "\n\t\t-=-=-= Dice Roll Game =-=-=-\n";
cout << "\n\nWhat's your name?\n";
getline(cin, playerName);
cout << "\nEnter your starting balance to play with : $";
cin >> balance;
game();
cont();
}
// function declaration
void cont()
{
cin >> choice;
if(choice == 'Y' || choice == 'y')
{
cout << "\n\n";
game();
}
else if (choice == 'N' || choice == 'n')
{
cout << "\n\nThanks for playing.";
}
else
{
cout << "\n\nInvalid input, please type 'y' or 'n'";
cont(); // calls itself (recursive function!!!)
}
}
void game()
{
do
{
cout << "\nYour current balance is $ " << balance << "\n";
cout << "Hey, " << playerName << ", enter amount to bet : $";
cin >> bettingAmount;
if(bettingAmount > balance)
cout << "\nBetting balance can't be more than current balance!\n" << "\nRe-enter bet\n";
} while(bettingAmount > balance);
// Get player's numbers
do
{
cout << "\nA dice will be rolled, guess the side facing up, any number between 1 and 6 : \n";
cin >> guess;
if(guess <= 0 || guess > 6 )
{
cout << "\nYour guess should be between 1 and 6\n" << "Re-enter guess:\n";
}
} while(guess <= 0 || guess > 6);
dice = rand() % 6+1;
diceRoll();
if (dice == guess)
{
cout << "\n\nYou guessed correctly! You won $" << (bettingAmount * 6);
balance = balance + (bettingAmount * 6);
}
else
{
cout << "\n\nYou guessed wrong. You lost $" << bettingAmount << "\n";
balance = balance - bettingAmount;
}
cout << "\n" << playerName << ", you now have a balance of $" << balance << "\n";
if (balance == 0)
{
cout << "You're out of money, game over";
}
cout << "\nDo you want to play again? type y or n : \n";
cont();
}
void diceRoll()
{
cout << "The winning number is " << dice << "\n";
}
|
Does it only take the first value?
Yes, the >> formatted extraction operator, when called for a single char value, will read the first non-whitespace character, and stop. Everything after it remains unread.
why does 'yy' cause a loop
Because the first "y" gets read, for the reasons explained above. The second "y" remains unread.
This is a very common mistake and a misconception about what >> does. It does not read an entire line of typed input. It only reads a single value after skipping any whitespace that precedes it.
Your program stops until an entire line of input gets typed, followed by Enter, but that's not what >> reads. It only reads what it's asked to read, and everything else that gets typed in remains unread.
So the program continues to execute, until it reaches this part:
cin >> bettingAmount;
At this point the next unread character in the input is y. The >> formatted extraction operator, for an int value like this bettingAmount, requires numerical input (following optional whitespace). But the next character is not numerical. It's the character y.
This results in the formatted >> extraction operator failing. Nothing gets read into bettingAmount. It remains completely unaltered by the >> operator. Because it is declared in global scope it was zero-initialized. So it remains 0.
In addition to the >> extraction operator failing, as part of it failing it sets the input stream to a failed state. When an input stream is in a failed state all subsequent input operation automatically fail without doing anything. And that's why your program ends up in an infinite loop.
Although there is a way to clear the input stream from its failed state this is a clumsy approach. The clean solution is to fix the code that reads input.
If your intent is to stop the program and enter something followed by Enter then that's what std::getline is for. The shown program uses it to read some of its initial input.
The path of least resistance is to simply use std::getline to read all input. Instead of using >> to read a single character use std::getline to read the next line of typed in input, into a std::string, then check the the string's first character and see what it is. Problem solved.
cin >> bettingAmount;
And you want to do the same thing here. Otherwise you'll just run into the same problem: mistyped input will result in a failed input operation, and a major headache.
Why do you need this headache? Just use std::getline to read text into a std::string, construct a std::istringstream from it, then use >> on the std::istringstream, and check its return value to determine whether it failed, or not. That's a simple way to check for invalid input, and if something other than numeric input was typed in here, you have complete freedom on how to handle bad typed in input.
|
70,546,571 | 70,546,781 | WSL Ubuntu showing "Error: Unable to open display" even after manually setting display environment variable | I'm using g++ on WSL Ubuntu. I cloned the GLFW repo using git, used the ccmake command to configure and generate the binaries, then used make inside the "build" directory to finally create the .a file. I installed all the OpenGL-related libraries to /usr/ld (I don't recall exactly which I installed, since I had to install so many. Regardless, the g++ command works, so I assume it was a success). Afterwards, I made a project on VS Code that looks like this:
The GLFW include-folder is from the aforementioned cloned repo, and the GLAD and KHR include-folders are from glad.dav1d.de, where I set the GL version (under API) to 3.3, and the Profile to Core.
In main.cpp, I put a simple snippet of code meant to initialize GLFW:
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
int main()
{
// Initialize GLFW
if (!glfwInit()) {
std::cerr << "Failed to initialize GLFW" << std::endl;
return 1;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
std::cout << "Success" << std::endl;
return 0;
}
Then used this to command to compile the project: g++ -Wall -I./include/ -L./lib/ src/*.{c,cpp} -lglfw3 -lGL -lX11 -lpthread -lXrandr -lXi -ldl -o main. There were no warnings or errors or anything. After running the executable, I get the error message that GLFW failed to initialize. I was a little confused why this happened, so I typed the glxinfo command to find out that my DISPLAY environment variable hasn't been set.
I have absolutely no idea what this variable is, or what it's meant to represent. After scouring around on the internet, I came across export DISPLAY=:0.0 and export DISPLAY=1 and export DISPLAY=IP:0.0, none of which worked. Any ideas on how I could resolve this?
| WSL on Windows 10 does not include support for GUI apps. You can build an app with OpenGL/X libraries, sure, but running it requires an X server on which to actually display it.
In general, you have 3 options. I believe all of these will work with OpenGL, although I have not tested each of them in that capacity:
The "supported" method is to use Windows 11 with WSLg. Windows 11 supports hardware-accelerated OpenGL in WSL2 out-of-the-box using a supported WDDMv3.0 driver (available for AMD, Intel, and nVidia GPUs). See Microsoft Docs for more information.
The "normal" method of running an X server on WSL with Windows 10 is to install a third-party X server such as VcXsrv. See this Super User question for some details on OpenGL support under that scenario. I don't believe that this will be hardware-accelerated, however.
You'll need to manually configure the DISPLAY variable in this case to point to your Windows host. You'll find some fairly complicated directions for doing so, but IMHO the easiest way is via mDNS.
Before upgrading to Windows 11, I used xrdp when I needed X support. This allows access to the WSL instance using the Remote Desktop Protocol and supported apps like the built-in Windows Remote Desktop Connection. I don't believe there is a way to hardware accelerate OpenGL using RDP, either. In my opinion, this is far easier than setting up a 3rd party X server. See my answer on Ask Ubuntu for steps to enable.
|
70,546,582 | 70,546,644 | Passing istream& to function, calls constructor? | I'm reading C++ Primer, Lippman et. al. 5/e.
Section 7.5.2. Delegating Constructors says,
class Sales_data {
friend std::istream &read(std::istream&, Sales_data&);
public:
// nondelegating constructor initializes members from corresponding arguments
Sales_data(std::string s, unsigned cnt, double price):
bookNo(s), units_sold(cnt), revenue(cnt*price) { }
// remaining constructors all delegate to another constructor
Sales_data(): Sales_data("", 0, 0) {}
Sales_data(std::string s): Sales_data(s, 0,0) {}
Sales_data(std::istream &is): Sales_data()
{ read(is, *this); }
// other members as before
};
*In this version of Sales_data, all but one of the constructors delegate their work. The first constructor takes three arguments, uses those arguments to initialize the data members, and does no further work. In this version of the class, we define the default constructor to use the three-argument constructor to do its initialization. It too has no additional work, as indicated by the empty constructor body. The constructor that takes a string also delegates to the three-argument version.
The constructor that takes an istream& also delegates. It delegates to the default constructor, which in turn delegates to the three-argument constructor. Once those constructors complete their work, the body of the istream& constructor is run. Its constructor body calls read to read the given istream.*
Function read is defined in section 7.1.3 as follows,
// input transactions contain ISBN, number of copies sold, and sales price
istream &read(istream &is, Sales_data &item)
{
double price = 0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = price * item.units_sold;
return is;
}
I'm confused about this line -
Once those constructors complete their work, the body of the istream& constructor is run. Its constructor body calls read to read the given istream.
is this correct ?
IMO, read is a global function which is not called on any object. Please correct my understanding if wrong and please help me clarify my doubt.
|
the istream& constructor
This is just a short-hand for "the constructor with a (single) parameter of type istream&". It may be a bit unlucky wording, since there is a possibility of confusion with "the constructor of istream&", but the difference is usually clear from context. Here it is obvious because it doesn't make sense to talk about the constructor of a reference type.
Suppose we give the constructors numbers:
/*1*/ Sales_data(std::string s, unsigned cnt, double price) //...
/*2*/ Sales_data(): Sales_data("", 0, 0) {}
/*3*/ Sales_data(std::string s): Sales_data(s, 0,0) {}
/*4*/ Sales_data(std::istream &is): Sales_data() //...
The quote is stating that a call to constructor 4 will first result in the execution of constructor 1 and 2 in that order before the body of 4 is executed.
The function body of constructor 4 contains a call to read. This is what "constructor body calls read" refers to. This is a completely usual function call and not related to constructors.
So the quote is correct.
IMO, read is a global function which is not called on any object.
The quote is not using the language "called on", so I don't really know what you mean here, but note that the call to read is not a call to a member function. There is no implicit object parameter involved like in a member function call of the form x.f(). It is a completely normal free function call as you could also use in any expression outside a class context.
|
70,546,590 | 70,563,007 | CGAL: identify "non-border" edges | I'm discovering CGAL, I tried the 3D convex hull. I tried it with the vertices of a cube, and I observed that the convex hull is a triangulation (I'm using Surface_mesh, not Polyhedron_3). So CGAL includes the diagonals of the faces of the cube in the list of edges. I want to identify such edges (because, for example, I don't want to plot these edges).
I expected that the function is_border would identify the other edges, but it returns false for all the edges. So what is a border?
I found a solution. I iterate over the edges and for each pair of the corresponding half-edges I take the attached face:
Mesh::Halfedge_index h0 = mesh.halfedge(ed, 0);
Mesh::Face_index face0 = mesh.face(h0);
Mesh::Halfedge_index h1 = mesh.halfedge(ed, 1);
Mesh::Face_index face1 = mesh.face(h1);
Then I compute the normals of these two faces, and I claim that the edge is a diagonal if these two normals are equal. Is it correct? That seems to work.
But my questions are:
what is a border, in the sense of is_border?
isn't there a more convenient way to identify the "non-border" edges (i.e. the diagonals in the case of the cube)?
| A border edge is an edge that is incident to only one face, meaning that you have a non-closed output. Obviously this cannot happen for a 3D convex hull, except if you are in a degenerate case and the point set is not 3D. You can use a geometric predicate (CGAL::coplanar() with the points of the edge and the opposite vertices of incident faces) even if we should get this information directly from the algorithm. I'll open an issue to get this information directly.
|
70,547,779 | 70,552,093 | Debug Assertion Failed Expression __acrt_first_block == header | I have been trying to figure out why this is happening and maybe it is just due to inexperience at this point but could really use some help.
When I run my code, which is compiled into a DLL using C++20, I get that a debug assertion has failed with the expression being __acrt_first_block == header.
I narrowed down where the code is failing, but the weird part is that it runs just fine when I change the Init(std::string filePath function signature to not contain the parameter. The code is below and hope someone can help.
Logger.h
#pragma once
#include "../Core.h"
#include <memory>
#include <string>
#include "spdlog/spdlog.h"
namespace Ruby
{
class RUBY_API Logger
{
public:
static void Init(std::string filePath);
inline static std::shared_ptr<spdlog::logger>& GetCoreLogger() { return coreLogger; }
inline static std::shared_ptr<spdlog::logger>& GetClientLogger() { return clientLogger; }
private:
static std::shared_ptr<spdlog::logger> coreLogger;
static std::shared_ptr<spdlog::logger> clientLogger;
};
}
Logger.cpp
namespace Ruby
{
std::shared_ptr<spdlog::logger> Logger::coreLogger;
std::shared_ptr<spdlog::logger> Logger::clientLogger;
void Logger::Init(std::string filePath)
{
std::string pattern{ "%^[%r][%n][%l]: %v%$" };
auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filePath, true);
// Setup the console and file sinks
std::vector<spdlog::sink_ptr> coreSinks;
coreSinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
coreSinks.push_back(fileSink);
// Bind the sinks to the core logger.
coreLogger = std::make_shared<spdlog::logger>("RUBY", begin(coreSinks), end(coreSinks));
// Set the Patterns for the sinks
coreLogger->sinks()[0]->set_pattern(pattern);
coreLogger->sinks()[1]->set_pattern(pattern);
// Tell spdlog to flush the file loggers on trace or worse message (can be changed if necessary).
coreLogger->flush_on(spdlog::level::trace);
// Set the default level of the logger
coreLogger->set_level(spdlog::level::trace);
// Do the same for the client logger
std::vector<spdlog::sink_ptr> clientSinks;
clientSinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
clientSinks.push_back(fileSink);
clientLogger = std::make_shared<spdlog::logger>("APP", begin(clientSinks), end(clientSinks));
clientLogger->sinks()[0]->set_pattern(pattern);
clientLogger->sinks()[1]->set_pattern(pattern);
clientLogger->flush_on(spdlog::level::trace);
clientLogger->set_level(spdlog::level::trace);
}
}
Entrypoint.h
#pragma once
#ifdef RB_PLATFORM_WINDOWS
extern Ruby::Application* Ruby::CreateApplication();
int main(int argc, char** argv)
{
Ruby::Logger::Init("../Logs/Recent_Run.txt");
RB_CORE_INFO("Initialized the logger.");
auto app = Ruby::CreateApplication();
app->Run();
delete app;
return 0;
}
#else
#error Ruby only supports windows
#endif // RB_PLATFORM_WINDOWS
| For anyone else who runs into a similar problem, here is how I fixed it.
Essentially the function signature for the Init() function was the problem. The std::string parameter was causing the debug assertion to fire, my best guess as of right now was because of move semantics but that part I am still not sure on. So there are a couple of ways that I found to fix this.
Method 1:
Make the parameter a const char*. I don't quite like this approach as it then relies on C style strings and if you are trying to write a program in modern C++, this is a huge step backwards.
Method 2:
Make the parameter a const std::string&. Making it a const reference to a string prevents the move semantics (again as far as I know) and the assertion no longer fires. I prefer this fix as it keeps the program in modern C++.
I hope this helps anyone who has similar issues, and be careful with statics and move semantics.
|
70,547,815 | 70,547,853 | What happens with extra spaces and newlines in C/C++ code? | Is there a difference between;
int main(){
return 0;
}
and
int main(){return 0;}
and
int main(){
return
0;
}
They will all likely compile to same executable. How does the C/C++ compiler treat the extra spaces and newlines, and if there is a difference between how newlines are treated differently than spaces in C code?
Also, how about tabs? What's the significance of using tabs instead of spaces in code, if there is any?
| Any sequence of 1+ whitespace symbol (space/line-break/tab/...) is equivalent to a single space.
Exceptions:
Whitespace is preserved in string literals. They can't contain line-breaks, except C++ raw literals (R"(...)"). The same applies to file names in #include.
Single-line comments (//) are terminated with line-breaks only.
Preprocessor directives (starting with #) are terminated with line-breaks only.
\ followed by a line-break removes both, allowing multi-line // comments, preprocessor directrives, and string literals.
Also, whitespace symbols are ignored if there is punctuation (anything except letters, numbers, and _) to the left and/or to the right of it. E.g. 1 + 2 and 1+2 are the same, but return a; and returna; are not.
Exceptions:
Whitespace is not ignored inside string literals, obviously. Nor in #include file names.
Operators consisting of >1 punctuation symbols can't be separated, e.g. cout < < 1 is illegal. The same applies to things like // and /* */.
A space between punctuation might be necessary to prevent it from coalescing into a single operator. Examples:
+ +a is different from ++a.
a+++b is equivalent to a++ +b, but not to a+ ++b.
Pre-C++11, closing two template argument lists in a row required a space: std::vector<std::vector<int> >.
When defining a function-like macro, the space is not allowed before the opening parenthesis (adding it turns it into an object-like macro). E.g. #define A() replaces A() with nothing, but #define A () replaces A with ().
|
70,547,875 | 70,549,816 | Strange behaviors of cuda kernel with infinite loop on different NVIDIA GPU | #include <cstdio>
__global__ void loop(void) {
int smid = -1;
if (threadIdx.x == 0) {
asm volatile("mov.u32 %0, %%smid;": "=r"(smid));
printf("smid: %d\n", smid);
}
while (1);
}
int main() {
loop<<<1, 32>>>();
cudaDeviceSynchronize();
return 0;
}
This is my source code, the kernel just print smid when thread index is 0 and then go to infinite loop, and the host just invoke the previous cuda kernel and wait for it. I run some experiments under 2 different configurations as following:
1. GPU(Geforce 940M) OS(Ubuntu 18.04) MPS(Enable) CUDA(v11.0)
2. GPU(Geforce RTX 3050Ti Mobile) OS(Ubuntu 20.04) MPS(Enable) CUDA(v11.4)
Experiment 1: When I run this code under configuration 1, the GUI system seems to get freezed because any graphical responses cannot be observed anymore, but as I press ctrl+c, this phenomena disappears as the CUDA process is killed.
Experiment 2: When I run this code under configuration 2, the system seems to work well without any abnormal phenomena, and the output of smid such as smid: 2\n can be displayed.
Experiment 3: As I change the block configuration loop<<<1, 1024>>> and run this new code twice under configuration 2, I get the same smid output such as smid: 2\nsmid: 2\n.(As for Geforce RTX 3050Ti Mobile, the amount of SM is 20, the maximum number of threads per multiprocessor is 1536 and max number of threads per block is 1024.)
I'm confused with these results, and here are my questions:
1. Why doesn't the system output smid under configuration 1?
2. Why does the GUI system seems to get freezed under configuration 1?
3. Unlike experiment 1, why does experiment 2 output smid normally?
4. In third experiment, the block configuation reaches to 1024 threads, which means that two different block cannot be scheduled to the same SM. Under MPS environment, all CUDA contexts will be merged into one CUDA context and share the GPU resource without timeslice anymore, but why do I still get same smid in the third experiment?(Furthermore, as I change the grid configuration into 10 and run it twice, the smid varies from 0 to 19 and each smid just appears once!)
|
Why doesn't the system output smid under configuration 1?
A safe rule of thumb is that unlike host code, in-kernel printf output will not be printed to the console at the moment the statement is encountered, but at the point of completion of the kernel and device synchronization with the host. This is the actual regime in effect in configuration 1, which is using a maxwell gpu. So no printf output is observed in configuration 1, because the kernel never ends.
Why does the GUI system seems to get freezed under configuration 1?
For the purpose of this discussion, there are two possible regimes: a pre-pascal regime in which compute-preemption is not possible, and a post-pascal regime in which it is possible. Your configuration 1 is a maxwell device, which is pre-pascal. Your configuration 2 is ampere device, which is post-pascal. So in configuration 2, compute preemption is working. This has a variety of impacts, one of which is that the GPU will service both GUI needs as well as compute kernel needs, "simultaneously" (the low level behavior is not thoroughly documented but is a form of time-slicing, alternating attention to the compute kernel and the GUI). Therefore in config 1, pre-pascal, kernels running for any noticeable time at all will "freeze" the GUI during kernel execution. In config2, the GPU services both, to some degree.
Unlike experiment 1, why does experiment 2 output smid normally?
Although its not well-documented, the compute preemption process appears to introduce an additional synchronization point, allowing for the flushing of the printf buffer, as mentioned in point 1. If you read the documentation I linked there, you will see that "synchronization point" covers a number of possibilities, and compute preemption seems to introduce (a new) one.
Sorry, won't be able to answer your 4th question at this time. A best practice on SO is to ask one question per question. However, I would consider usage of MPS with a GPU that is also servicing a display to be "unusual". Since we've established that compute preemption is in effect here, it may be that due to compute-preemption as well as the need to service a display, the GPU services clients in a round-robin timeslicing fashion (since it must do so anyway to service the display). In that case the behavior under MPS may be different. Compute preemption allows for the possibility of the usual limitations you are describing to be voided. One kernel can completely replace another.
|
70,548,248 | 70,548,329 | Calling `.lock()` on weak_ptr returns NULL shared_ptr | I am somewhat confused by the behaviour of the .lock() call on a weak_ptr. My understanding is that .lock() will return a shared_ptr of the relevant type if it has not expired otherwise it will be a null pointer.
From https://en.cppreference.com/w/cpp/memory/weak_ptr/lock :
A shared_ptr which shares ownership of the owned object if std::weak_ptr::expired returns false.
This is however not the outcome I am seeing. The code below is a method of the Unit class that should return a shared_ptr to the Unit's parent:
unsigned Unit::getParentId() const {
auto parent = parent_.lock();
return parent->getId();
}
The debugger output below shows that parent_ exists as a weak_ptr. However when I call auto parent = parent_.lock();, it returns a NULL pointer as can be seen in the last line of the debugger output.
I am obviously missing something really basic here?
this = {const Unit *} 0x16f1af010
id_ = {unsigned int} 234
name_ = {std::string} "Test"
parent_ = {std::weak_ptr<Unit>} std::__1::weak_ptr<Unit>::element_type @ 0x00006000034d00d8 strong=0 weak=2
__ptr_ = {std::weak_ptr<Unit>::element_type *} 0x6000034d00d8
id_ = {unsigned int} 0
name_ = {std::string} "Root"
parent_ = {std::weak_ptr<Unit>} nullptr
children_ = {std::vector<std::shared_ptr<Unit>>} size=0
children_ = {std::vector<std::shared_ptr<Unit>>} size=0
parent = {std::shared_ptr<Unit>} nullptr
__ptr_ = {std::shared_ptr<Unit>::element_type *} NULL
| Weak pointer attaches only to existing shared pointers, by itself weak pointer doesn't hold or create any object pointer. In other words if you do:
std::weak_ptr<int> wp;
auto sp = wp.lock();
then it always returns nullptr. You have to pass Existing shared pointer in constructor or through assignment (=), e.g.
std::shared_ptr<int> sp = std::make_shared<int>();
std::weak_ptr<int> wp(sp);
auto spl = wp.lock(); // now spl is not null
or through assignment
std::shared_ptr<int> sp = std::make_shared<int>();
std::weak_ptr<int> wp;
wp = sp;
auto spl = wp.lock(); // now spl is not null
As long as all copies of shared pointer still exist then weak pointer will return non null on lock. Otherwise if no copies of shared pointer exist then weak pointer will always return null.
In your case you don't have any copies of shared pointers hence weak pointer will alway return null on lock in such case.
|
70,548,260 | 70,548,300 | C++ windows.h - window doesnt open | #include<windows.h>
#include<iostream>
#include<tchar.h>
LRESULT CALLBACK WindowProcedure(HWND, UINT, WPARAM, LPARAM);
TCHAR szClassName[ ] = _T("ClassName");
int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow)
{
HWND hwnd;
MSG messages;
WNDCLASSEX wincl;
wincl.hInstance = hThisInstance;
wincl.lpszMenuName = szClassName;
wincl.lpfnWndProc = WindowProcedure;
wincl.style = CS_DBLCLKS;
wincl.cbSize = sizeof(WNDCLASSEX);
wincl.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wincl.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wincl.hCursor = LoadCursor(NULL, IDC_ARROW);
wincl.cbClsExtra = 0;
wincl.cbWndExtra = 0;
wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
if (!RegisterClassEx(&wincl))
return 0;
hwnd = CreateWindowEx(0, szClassName, _T("ClassName"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 544, 375, HWND_DESKTOP, NULL, hThisInstance, NULL);
ShowWindow(hwnd, nCmdShow);
while(GetMessage(&messages, NULL, 0, 0))
{
TranslateMessage(&messages);
DispatchMessage(&messages);
}
return messages.wParam;
}
LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
The window doesnt show up/open. I've tried for 6 hours straight to find the problem, it doesn't give me an error in the console, it just creates the .exe window but not the other window. I'm new to this, so idk what to do or how to reply to this.
| This statement is wrong:
wincl.lpszMenuName = szClassName;
It needs to be this instead:
wincl.lpszClassName = szClassName;
You are not checking if CreateWindowEx() fails (returns NULL):
hwnd = CreateWindowEx(...);
if (hWnd == NULL) ... // <-- ADD THIS
In this situation, it does fail, because you are not registering the class name correctly, so creating the window will report an ERROR_CANNOT_FIND_WND_CLASS (1407) error from GetLastError().
|
70,548,510 | 70,549,071 | what is the difference between const char * and const char ()[] | I found this function in some library that I would like to use but I can't figure out out to pass a std::string variable to it
----------
template<int KeyLen>
std::vector<unsigned char> key_from_string(const char (*key_str)[KeyLen]) {
std::vector<unsigned char> key(KeyLen - 1);
memcpy(&key[0], *key_str, KeyLen - 1);
return key;
}
test_encryption.cpp
const std::vector<unsigned char> key2 = plusaes::key_from_string(usr_key.c_str());
this is how i am trying to call that function
Error
test_encryption.cpp: In function 'std::__cxx11::string encrypte_string(std::__cxx11::string, std::__cxx11::string)':
test_encryption.cpp:39:82: error: no matching function for call to 'key_from_string(const char*)'
const std::vector<unsigned char> key2 = plusaes::key_from_string(usr_key.c_str()); // 16-char = 128-bit
^
In file included from test_encryption.cpp:1:
pulse.hpp:685:35: note: candidate: 'std::vector<unsigned char> plusaes::key_from_string(const char (*)[17])'
inline std::vector<unsigned char> key_from_string(const char (*key_str)[17]) {
^~~~~~~~~~~~~~~
pulse.hpp:685:35: note: no known conversion for argument 1 from 'const char*' to 'const char (*)[17]'
pulse.hpp:690:35: note: candidate: 'std::vector<unsigned char> plusaes::key_from_string(const char (*)[25])'
inline std::vector<unsigned char> key_from_string(const char (*key_str)[25]) {
^~~~~~~~~~~~~~~
pulse.hpp:690:35: note: no known conversion for argument 1 from 'const char*' to 'const char (*)[25]'
pulse.hpp:695:35: note: candidate: 'std::vector<unsigned char> plusaes::key_from_string(const char (*)[33])'
inline std::vector<unsigned char> key_from_string(const char (*key_str)[33]) {
^~~~~~~~~~~~~~~
pulse.hpp:695:35: note: no known conversion for argument 1 from 'const char*' to 'const char (*)[33]'
| The function in the library only accepts pointers to string literals. Example:
std::vector<unsigned char> key = plusaes::key_from_string(&"Foo");
Here KeyLen would be deduced to 4 because the string literal consists of 'F', 'o', 'o', '\0'
You supply usr_key.c_str() to the function, which returns a const char*, and that's not a match to such a function. All template parameters must be known at compile time and KeyLen is such a parameter. It must be a compile time constant.
An alternative is to create the std::vector<unsigned char> manually:
std::vector<unsigned char> key2(usr_key.begin(), usr_key.end());
or if you want, create your own helper function:
std::vector<unsigned char> my_key_from_string(const std::string& s) {
return {s.begin(), s.end()};
}
and use it like so:
auto key2 = my_key_from_string(usr_key);
|
70,549,068 | 70,549,177 | Does creating an object directly in a vector, and then removing it from the vector, calls to a destructor? | Say i have a class named test, and a vector
std::vector<test> Tests;
If i execute this code:
Tests.push_back(test());
and then
Tests.pop_back();
What happens to the test object? Is its destructor being called upon?
| This example might show a little bit better what happens.
Live demo here : https://onlinegdb.com/c6-N-vyPc
Output will be :
Creating first vector (push_back)
>>>> Test constructor called
>>>> Test move constructor called
<<<< Test destructor called
Destroying first vector
<<<< Test destructor called
Creating second vector (emplace_back)
>>>> Test constructor called
Destroying second vector
<<<< Test destructor called
Example code :
#include <iostream>
#include <vector>
class Test
{
public:
Test()
{
std::cout << ">>>> Test constructor called\n";
}
Test(const Test&)
{
std::cout << ">>>> Test copy constructor called\n";
}
Test(Test&&)
{
std::cout << ">>>> Test move constructor called\n";
}
~Test()
{
std::cout << "<<<< Test destructor called\n";
}
};
int main()
{
// scope to manage life cycle of vec1
{
std::cout << "\nCreating first vector (push_back)\n";
std::vector<Test> vec1;
vec1.push_back(Test{});
std::cout << "Destroying first vector\n";
}
// scope to manage life cycle of vec2
{
std::cout << "\nCreating second vector (emplace_back)\n";
std::vector<Test> vec2;
vec2.emplace_back();
std::cout << "Destroying second vector\n";
}
return 0;
}
|
70,549,378 | 70,550,658 | Why we need to add the "ranges" when calculate ha_innobase::read_time? | We see that MySQL needs to add the ranges when calculate the ha_innobase::read_time (/storage/innobase/handler/ha_innobase.cc), my question is why it need it?
double ha_innobase::read_time(
uint index, /*!< in: key number */
uint ranges, /*!< in: how many ranges */
ha_rows rows) /*!< in: estimated number of rows in the ranges */
{
ha_rows total_rows;
if (index != table->s->primary_key) {
/* Not clustered */
return(handler::read_time(index, ranges, rows));
}
if (rows <= 2) {
return((double) rows);
}
/* Assume that the read time is proportional to the scan time for all
rows + at most one seek per range. */
double time_for_scan = scan_time();
if ((total_rows = estimate_rows_upper_bound()) < rows) {
return(time_for_scan);
}
return(ranges + (double) rows / (double) total_rows * time_for_scan);
}
| This comment tells you the answer:
/* Assume that the read time is proportional to the scan time for all
rows + at most one seek per range. */
There is probably a seek for each range, and each seek increases the read time. Seeks were more costly on spinning storage devices, and most sites now use solid-state storage, but seeks are still a little bit costly. So it's important to count them when calculating the total read time.
|
70,549,518 | 70,550,109 | How to address a typedefed inner class of a class template that itself is a template? | I have a syntactic question rather,
With the following iterator class inside of a vector class,
#include <memory>
#include <cstddef>
#include <iterator>
namespace ft { template <class T, class Alloc = std::allocator<T> > class vector; }
template <class T, class Alloc>
class ft::vector
{
public:
typedef T value_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::pointer pointer;
typedef ptrdiff_t difference_type;
template <class value_type>
class ptr_iterator : public std::iterator<std::random_access_iterator_tag, value_type>
{
public:
ptr_iterator();
};
typedef ptr_iterator<value_type> iterator;
typedef ptr_iterator<const value_type> const_iterator;
};
How can I address the constructor of ptr_iterator outside of the declaration?
I tried this way:
template <class T, class Alloc>
ft::vector<T, Alloc>::iterator::iterator() {}
But it yields
Vector.hpp:120:1: error: specializing member 'ft::vector<T, Alloc>::ptr_iterator<T>::iterator' requires 'template<>' syntax
ft::vector<T, Alloc>::iterator::iterator() {}
I attempted adding <> after both of the iterator words and replacing the second iterator word with ptr_iterator, but it still doesn't compile.
Can I still use the typedef without repeating both templates above the function signature?
Or is there a better design for the iterator declaration that'll allow me to define both iterator and const_iterator?
| For the out-of-line definition, you must unfortunately repeat the entire "signature" of all the nested templates, including constraints, if any. Cigien has given the right form:
template <class T, class Alloc>
template <class value_type>
ft::vector<T, Alloc>::ptr_iterator<value_type>::ptr_iterator()
{}
Since this can be messy and error-prone, you can also define the nested class inline, or alternatively as a non-nested helper class. In libstdc++, the former approach is taken for the iterators of views, but the latter for containers like std::vector, for example:
typedef __gnu_cxx::__normal_iterator<pointer, vector> iterator;
typedef __gnu_cxx::__normal_iterator<const_pointer, vector>
const_iterator;
Edit:
Oh dear, I'm not sure if it's even possible to define an operator like that! Since it's a free function, it doesn't need the nested template parameters and I would put it in the ft namespace. It would have to look like this:
namespace ft {
template <class T, class Alloc, class value_type>
bool operator==(
typename vector<T, Alloc>::template ptr_iterator<value_type> const& lhs,
typename vector<T, Alloc>::template ptr_iterator<value_type> const& rhs)
{ return true; }
}
However, I've tried this code on Compiler Explorer and my compiler complains that it cannot deduce the parameter(s) of the vector class.
|
70,549,812 | 70,550,011 | Snake Game going too fast console c++ | I've been following a few tutorials for making a somewhat Snake Game , just not a full-tailed-one , It's going alright and i think i got it almost right but I've got two problems
#include <bits/stdc++.h>
#include <conio.h>
#include <unistd.h>
using namespace std;
int side,x,y;
int fruitx,fruity,score,flag;
bool isOver;
void randomize();
void frame(int);
void userinp();
void game();
int main(){
do{
cout << "Enter the side of your frame!(not less than 20)\n";
cin >> side;
}while(side < 20);
randomize();
while(!isOver){
frame(side);
userinp();
game();
}
return 0;
}
void randomize(){
x = side/2;
y = side/2;
label1: fruitx = rand()%side;
if (fruitx == 0 || fruitx == side)
goto label1;
label2:
fruity = rand()%side;
if (fruity == 0 || fruity == side)
goto label2;
score = 0;
}
void frame(int s){
system("cls");
for(int i=1;i<=s;i++){
for(int j=1;j<=s;j++){
if(i == 1 || i == s || j == 1 || j == s)
cout << "*";
else{
if(i == x && j == y){
cout << "-";
}
else if(i == fruitx && j == fruity){
cout << "x";
}
else
cout << " ";
}
}
cout << "\n";
}
cout << "Your score: " << score << endl;
}
void userinp(){
if(kbhit()){
switch (getch()){
case 'a':
flag = 1;
break;
case 's':
flag = 2;
break;
case 'd':
flag = 3;
break;
case 'w':
flag = 4;
break;
default:
isOver = true;
}
}
}
void game(){
sleep(0.899);
switch (flag){
case 1:
y--;
break;
case 2:
x++;
break;
case 3:
y++;
break;
case 4:
x--;
break;
}
if (x < 0 || x > side || y < 0 || y > side){
x = side/2;
y = side/2;
}
if (x == fruitx && y == fruity) {
label3: fruitx = rand()%(side);
if (fruitx == 0)
goto label3;
label4: fruity = rand()%(side);
if (fruity == 0)
goto label4;
score++;
}
}
the first problem:
using
system"(cls")
helped with the screen not going down way many times to avoid the screen scrolling down i tried it to make the screen clear every time the sleep() is called but i cannot get how to slow down the process a bit using the sleep() function , It's either too slow or too fast The screen , Is there a different way to approach the whole thing or is the function itself not proper to use here ?
second problem:
whenever i input the side with 20 , i cannot find the fruit itself at all but when it is any number more than this it does show me the random fruits just fine so is there a way to fix why at just side = 20 it would not work ?
PS: If there is anything that could be improved aside from these 2 problems i'd appreciate it .. Thanks in advance!
| First sleep is a bit rough. See answers here for better solutions: Sleep for milliseconds
Second you don't account for your own overhead. Your program might run faster/slower on different setups. For games in general you want to use a somewhat precise but fast time function to get an idea of how much to move everything (granted not really needed for snake). For more suggestions on this topic see this quesiton: How to Make a Basic FPS Counter?
Last the console is not really good for this sort of application. I would suggest switching to a simple GUI, just so you don't have to deal with the console craziness. If your goal is to have some sort of demo to learn something and move on it might be ok, and live with the strange behavior.
For the issue with the fruit:
NEVER use goto. It's very hard to reason about it and for the standard tools to deal with it. Use functions/loops that are easier reason about. In your case a do{ friutx = ...; } while (friuitx==0) would do.
The two places where you setup the fruit use different code. Likely even if you fix one, the other might still be broken. Create a function and call it from both places.
% will do a reminder (0 to side-1, inclusive). Looks like your target is 2 to side-1, so maybe do rand()%(side-1) + 1 or better yet, use std::uniform_int_distribution.
It's not clear to me why it's not seen correctly. Use a debugger to check when you are rendering a frame what are the coordinates of the fruit. They might overlap the edges and be replaced with a *.
|
70,549,850 | 70,549,930 | weakly_incrementable constraint while using iota_view | To quickly create a for loop similar to python's for i in range(100), I could do:
for (auto const i : std::views::iota(0, 100))
{ /* ... */ }
However, CLion is warning me to add a std::weakly_incrementable constraint to my auto:
for (std::weakly_incrementable auto const i : std::views::iota(0, 100))
{ /* ... */ }
I know that the starting value of iota_view must be weakly_incrementable, and I would assume that auto i will create an i that is the same type of the starting value.
But is it true? Is it possible for it to create something of a totally different type (not even weakly incrementable)? And can I safely ignore the warning?
|
Is it possible for it to create something of a totally different type
(not even weakly incrementable)? And can I safely ignore the warning?
According to the synopsis of iota_view in [range.iota.view]:
template<weakly_incrementable W, semiregular Bound = unreachable_sentinel_t>
class iota_view : public view_interface<iota_view<W, Bound>> {
//...
};
It is already constrained W must be weakly_incrementable. And since iota_view::iterator::operator*() returns the same type as W, you can ignore this warning.
|
70,550,071 | 70,550,224 | How do you convert a `std::string` hex value to an `unsigned char` | sample input
a8 49 7f ac 24 77 c3 6e 70 ca 99 ca fc e2 c5 7b
This fucntion converts the hex values in the sample to a string to be later converted into an unsigned char
std::vector<unsigned char> cipher_as_chars(std::string cipher)
{
std::vector<unsigned char> hex_char;
int j =0 ;
for (int i = 0; i < cipher.length();)
{
std::string x = "";
x = x + cipher[i] + cipher[i+1];
unsigned char hexchar[2] ;
strcpy( (char*) hexchar, x.c_str() );
hex_char[j] = *hexchar;
j++;
cout << "Current Index : " << i << " " << x << " <> " << hexchar << endl;
i = i+3;
}
return hex_char;
}
| As a very simple solution, you can use a istringstream, which allows parsing hex strings:
#include <cstdio>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
std::vector<unsigned char> cipher_as_chars(std::string const& cipher) {
std::istringstream strm{cipher};
strm >> std::hex;
return {std::istream_iterator<int>{strm}, {}};
}
int main() {
auto const cipher = "a8 49 7f ac 24 77 c3 6e 70 ca 99 ca fc e2 c5 7b";
auto const sep = cipher_as_chars(cipher);
for (auto elm : sep) {
std::printf("%hhx ", elm);
}
std::putchar('\n');
}
|
70,550,162 | 70,550,204 | Sort words alphabetically but "ch" is more than "h" using qsort with saving it as upper case | I just cant figure out, how to sort a char array (NO VECTOR) of words alphabetically. Because our alphabet has "ch" which is "bigger" than "h", so I need every word starting with "ch" go behind "h".
This is mine current code of sorting, but i cant fogure it out, how to add "ch more than h" rule.
And im using here "everything compare and save as upper" policy, because mine bigger project need it.
int compare(const void *a, const void *b) {
char *one = *(char **) b;
one = to_uppercase(one);
char *two = *(char **) a;
two = to_uppercase(two);
return strcmp(one , two);
}
void sortit(char **list, int lenght) {
qsort(list, lenght, sizeof(char *), compare);
}
Thanks
| You'll need to define your own comparison function.
[IMPORTANT] Notice this solution only looks at the first character. I.e. "aching" and "advert" will be ordered as ["aching", "advert"], and not as ["advert", "aching"], even when 'ch' should come after 'd'.
[Demo]
#include <algorithm> // sort
#include <iostream> // cout
#include <string>
#include <vector>
int main()
{
std::vector<std::string> words{ "apple", "car", "cherry", "hugo", "boss" };
auto my_words_cmp = [](auto& w1, auto& w2) {
if (w1.size() > 1 and w2.size() > 0 and w1.substr(0, 2) == "ch" and w2[0] <= 'h') { return false; }
else if (w1.size() > 0 and w2.size() > 1 and w1[0] <= 'h' and w2.substr(0, 2) == "ch") { return true; }
else return (w1 < w2);
};
std::sort(std::begin(words), std::end(words), my_words_cmp);
for (auto& w : words) { std::cout << w << " "; }
}
// Outputs
// apple boss car hugo cherry
[EDIT] Taking into account the comments from other users, here's an implementation that sorts the strings taking into account that 'ch' can appear anywhere:
Walk each input word (if any of them contains a 'ch'; otherwise compare them straight away and return).
Map each character, including 'ch', to an int value: 0 for 'a', 8 for 'h', 9 for 'ch', 10 for 'i'...
Then compare the two vectors.
[Demo]
#include <algorithm> // sort, transform
#include <iostream> // cout
#include <string>
#include <vector>
int main()
{
std::vector<std::string> words{ "aching", "advert", "m", "d", "ch", "a" };
auto my_words_cmp = [](auto& w1, auto& w2) {
if (w1.find("ch") == std::string::npos and w2.find("ch") == std::string::npos) { return w1 < w2; }
std::vector<int> v1(w1.size());
std::vector<int> v2(w2.size());
auto weight_char = [](auto& c1, auto& c2) {
if (c1 == 'c' and c2 == 'h') { return 'h' - 'a' + 1; }
else if (c1 <= 'h') { return c1 - 'a'; }
else { return c1 - 'a' + 1; }
};
std::transform(std::begin(w1), std::end(w1), std::next(std::begin(w1)), std::begin(v1), weight_char);
std::transform(std::begin(w2), std::end(w2), std::next(std::begin(w2)), std::begin(v2), weight_char);
return v1 < v2;
};
std::sort(std::begin(words), std::end(words), my_words_cmp);
for (auto& w : words) { std::cout << w << " "; }
}
// Outputs:
// advert aching d ch m
|
70,550,535 | 70,550,585 | creating vector using new operator | I have an assignment and the question is "write a function that creates a vector of user-given size M using new operator"
Code:
#include <iostream>
#include <vector>
int main()
{
int user_size;
std::cin >> user_size;
int *p = new std::vector<int> g5(user_size);
delete p;
return 0;
}
pls give me any advice how can I improve the code(obviously my knowledge improves too) and this code doesn't feel right to me.
| It's unclear, what is meant here by vector. Moreover, the assignment says nothing about the type of the data. If vector is meant to be an array of M then the following
int*array = new int[M];
is the appropriate command (here assuming int as data type). In this case, you will need to delete the array later using the delete[] rather than plain delete, i.e.
delete[] array;
On the other hand, if vector refers to std::vector, then
std::vector<int> *pvec = new std::vector<int>(M);
is appropriate. However, this is really bad code, as std::vector under the hood allocates its data using new anyway, implying that this type of code generates a double reference and unnecessary memory allocation. Now you must use plain delete for destroying the object:
delete pvec;
|
70,550,617 | 70,550,686 | Is there a way to make the compiler include functions from outer scopes when picking a candidate? | Consider this class and variadic member function:
class foo
{
public:
template<class C, class... Cs>
void add(C&& c, Cs&&... cs)
{
...
add(cs...);
}
private:
void add(){ }
};
Is there a way to place the empty add overload that terminates the recursion inside another scope? Please ignore whether or not this is generally a good idea, I am strictly asking for how one could do it, if at all. I would like to place it inside an impl namespace like so:
namespace impl
{
void add() {}
}
class foo
{
public:
template<class C, class... Cs>
void add(C&& c, Cs&&... cs)
{
...
using namespace impl;
add(cs...);
}
};
But the above code does not work when instatiated. The compiler complains that it can't find a matching function call for add when the parameter pack is empty.
Is there a way to achieve this using some scope-hackery?
| How about using if constexpr:
namespace impl { void add() {} }
class foo {
public:
template<class C, class... Cs>
void add(C&& c, Cs&&... cs)
{
if constexpr (sizeof...(Cs) == 0)
impl::add();
else
add(cs...);
}
};
|
70,550,713 | 70,551,926 | Hash function for a smart pointer class as key for an unordered map | So, I have a pointer wrapper class which stores only a pointer and I need to use this class instance as a key in an unordered map. I currently have a similar setup with this pointer wrapper instances as keys to a std::map by overriding bool operator< but for an unordered map setup I would need to override two other operators == and (). I've figured how == operator implementation would be. but not sure about an implementation for the () operator. what sort of hash implementation setup should I be doing in this case? I've checked in places and most examples cover non pointer cases and they use two Key items and form hash for each and compare them for () implementation.
template <class T>
class PointerWrap{
public:
T* pointer;
bool operator<(const PointerWrap& other)const{return *pointer < *other.pointer;}
bool operator==(const PointerWrap& other)const{return *pointer == *other.pointer;}
//size_t operator()(const PointerWrap& other)const{return (*pointer)(*other.pointer);}
};
class VarType{
bool operator<(const VarType& other)const{return this < &other;}
bool operator==(const VarType& other)const{return this == &other;}
size_t operator()(const VarType& other)(.?.?.}
};
//Desired setup.
std::unordered_map<PointerWrap<VarType>,Value> mymap;
| Since you seem to need a hash function only for using PointerWrappers in an unordered map, the hash function in the standard library should serve you well. (But these are not cryptographically secure hash functions so don't use them for anything else). Here is some code to show how to do this:
#include <unordered_map>
#include <iostream>
template <class T>
class PointerWrap {
public:
T* pointer;
bool operator<(const PointerWrap& other)const { return *pointer < *other.pointer; }
bool operator==(const PointerWrap& other)const { return *pointer == *other.pointer; }
size_t operator()(const PointerWrap& other) const {return (*pointer)(*other.pointer);}
};
class VarType {
public: // PointerWrap has no access to these operators without a public access specifier
bool operator<(const VarType& other)const { return this < &other; }
bool operator==(const VarType& other)const { return this == &other; }
// Pointless to hash a object without any data
std::size_t operator()(const VarType& other)const {
return 0;
}
};
// Specialization of std::hash for PointerWrap<T>
template<typename T>
class std::hash<PointerWrap<T>> {
public:
size_t operator()(PointerWrap<T> v) const{
return std::hash<T*>()(v.pointer);
}
};
int main() {
// your desired setup compiles.
std::unordered_map<PointerWrap<VarType>, int> mymap;
PointerWrap<VarType> a;
mymap[a] = 5;
std::cout << mymap[a] << std::endl;
return 0;
}
|
70,550,907 | 70,551,347 | How would one efficiently reuse code in a specialised template struct? | I am creating my own vector struct for a maths library.
Currently, I would create the struct somewhat like this:
template <unsigned int size, typename T>
struct vector {
// array of elements
T elements[size];
// ...
};
However, the main use case of the maths library will lead to mostly making use of 2-dimensional, 3-dimensional, and 4-dimensional vectors (commonly vec2, vec3, and vec4). Because of this, a useful feature would be the ability to access the x, y, z, and w values from the vector when possible. However, there are some problems with this.
The x, y, z, and w members would need to be reference variables to elements[0], elements[1], etc. This means that, if the vector has less than 4 elements, some references would not be initialised.
Of course, this is possible to achieve with specialised templates, and this is what I am currently doing:
template <unsigned int size, typename T>
struct vector {
// ...
}
template <typename T>
struct vector<2, T> {
// same as with before, except with references to X and Y elements.
// these are successfully initialised in the constructor because the vector is guaranteed to have 2 elements
T &x;
T &y;
// ...
}
// and so on for 3D and 4D vectors
This works, but it is far from convenient. In practice, the vector struct is large and has a lot of functions and operator overloads. When it is specialised into the other sizes, these functions and operator overloads need to be copy+pasted from the generic struct to 2D, 3D and 4D structs, which is very inefficient. Keep in mind: the only thing I'm changing between specialisations is the reference variables! All other members are the exact same, and so I'd rather reuse their code.
One other solution is to inherit from one base class. I'm not entirely sure how to do this in a way that allows the inherited operator overloads to return the values from the child vector structs rather than the values from the parent struct.
So, my question is: how would I efficiently reuse the code in a specialised template struct whilst still being able to have (in this case) the x, y, z, and w references, when available?
| As correctly noted in comments for another answer, having reference fields is a big pain because you cannot reassign references, hence operator= is not generated automatically. Moreover, you cannot really implement it yourself. Also, on a typical implementation a reference field still occupies some memory even if it points inside the structure.
However, for completeness, here is my answer: in C++ metaprogramming, if you need to dynamically add/remove fields into a class, you can use inheritance. You may also use Curiously Recurring Template Pattern (CRTP) to access the derived struct from the base.
One possible implementation is below. vector_member_aliases<size, T, Derived> is a base for a class Derived which provides exactly min(0, size) member references with names from x, y, z, w. I also use inheritance between them to avoid code duplication.
#include <iostream>
template <unsigned int size, typename T, typename Derived>
struct vector_member_aliases : vector_member_aliases<3, T, Derived> {
T &w = static_cast<Derived*>(this)->elements[3];
};
template <typename T, typename Derived>
struct vector_member_aliases<0, T, Derived> {};
template <typename T, typename Derived>
struct vector_member_aliases<1, T, Derived> : vector_member_aliases<0, T, Derived> {
T &x = static_cast<Derived*>(this)->elements[0];
};
template <typename T, typename Derived>
struct vector_member_aliases<2, T, Derived> : vector_member_aliases<1, T, Derived> {
T &y = static_cast<Derived*>(this)->elements[1];
};
template <typename T, typename Derived>
struct vector_member_aliases<3, T, Derived> : vector_member_aliases<2, T, Derived> {
T &z = static_cast<Derived*>(this)->elements[2];
};
template <unsigned int size, typename T>
struct vector : vector_member_aliases<size, T, vector<size, T>> {
// array of elements
T elements[size]{};
void print_all() {
for (unsigned int i = 0; i < size; i++) {
if (i > 0) {
std::cout << " ";
}
std::cout << elements[i];
}
std::cout << "\n";
}
};
int main() {
[[maybe_unused]] vector<0, int> v0;
// v0.x = 10;
vector<1, int> v1;
v1.x = 10;
// v1.y = 20;
v1.print_all();
vector<2, int> v2;
v2.x = 11;
v2.y = 21;
// v2.z = 31;
v2.print_all();
vector<3, int> v3;
v3.x = 12;
v3.y = 22;
v3.z = 32;
// v3.w = 42;
v3.print_all();
vector<4, int> v4;
v4.x = 13;
v4.y = 23;
v4.z = 33;
v4.w = 43;
v4.print_all();
std::cout << sizeof(v4) << "\n";
}
Another implementation is to create four independent classes and use std::condition_t to choose from which to inherit, and which to replace with some empty_base (distinct for each skipped variable):
#include <iostream>
#include <type_traits>
template<int>
struct empty_base {};
template <typename T, typename Derived>
struct vector_member_alias_x {
T &x = static_cast<Derived*>(this)->elements[0];
};
// Skipped: same struct for for y, z, w
template <unsigned int size, typename T>
struct vector
: std::conditional_t<size >= 1, vector_member_alias_x<T, vector<size, T>>, empty_base<0>>
, std::conditional_t<size >= 2, vector_member_alias_y<T, vector<size, T>>, empty_base<1>>
, std::conditional_t<size >= 3, vector_member_alias_z<T, vector<size, T>>, empty_base<2>>
, std::conditional_t<size >= 4, vector_member_alias_w<T, vector<size, T>>, empty_base<3>>
{
// ....
};
|
70,550,983 | 70,552,118 | http request using sockets on c++ | I'm trying to do an HTTP request using sockets on Linux, and my function works now, but only with simple domains as www.google.com or webpage.000webhostapp.com. When I try to add a path and query like webpage.000webhostapp.com/folder/file.php?parameter=value, it starts failing.
This is my code:
#include <iostream>
#include <cstring>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
int main(){
int socket_desc;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[4096];
std::string url = "www.exampleweb.com/folder/file.php";
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if(socket_desc < 0){
std::cout<<"failed to create socket"<<std::endl;
}
server = gethostbyname(url.c_str());
if(server==NULL){std::cout<<"could Not resolve hostname :("<<std::endl;}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(80);
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
if(connect(socket_desc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
std::cout<<"connection failed :("<<std::endl;
}
std::string request = "GET / HTTP/1.1\r\nHost: " + url + "\r\nConnection: close\r\n\r\n";
if(send(socket_desc, request.c_str(), strlen(request.c_str())+1, 0) < 0){
std::cout<<"failed to send request..."<<std::endl;
}
int n;
std::string raw_site;
while((n = recv(socket_desc, buffer, sizeof(buffer)+1, 0)) > 0){
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r'){
raw_site+=buffer[i];
i += 1;
}
}
std::cout<<raw_site<<std::endl;
return 0;
}
Using www.google.com, it works perfectly for the request.
Using www.example.com/folder/file.php?parameter=value¶meter2=value2, it fails and returns "could not resolve hostname".
Any idea on how to fix it?
I'm not using curl and can't use it for this project.
| gethostbyname() (which BTW is deprecated, you should be using getaddrinfo() instead) does not work with URLs, only with host names.
Given a URL like http://www.exampleweb.com/folder/file.php?parameter=value¶meter2=value2, you need to first break it up into its constituent pieces (read RFC 3986), eg:
the scheme http
the host name www.exampleweb.com
the resource path /folder/file.php
the query ?parameter=value¶meter2=value2
You can then resolve the IP address for the host, connect to that IP address on port 80 (the default port for HTTP) since the URL doesn't specify a different port, and finally send a GET request for the resource and query.
Also, note that the Host header in the GET request must specify only the host name (and port, if different than the default), not the whole URL. And also that HTTP requests are not null-terminated strings, so do not send the null terminator. Read RFC 2616.
Try this instead:
#include <iostream>
#include <cstring>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
int main(){
int socket_desc;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[4096];
std::string host = "www.exampleweb.com";
std::string port = "80";
std::string resource = "/folder/file.php";
std::string query = "?parameter=value¶meter2=value2";
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc < 0){
std::cout << "failed to create socket" << std::endl;
return 0;
}
server = gethostbyname(host.c_str());
if (server == NULL){
std::cout << "could Not resolve hostname :(" << std::endl;
close(socket_desc);
return 0;
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(std::stoi(port));
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
if (connect(socket_desc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
std::cout << "connection failed :(" << std::endl;
close(socket_desc);
return 0;
}
std::string request = "GET " + resource + query + " HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n";
if (send(socket_desc, request.c_str(), request.size(), 0) < 0){
std::cout << "failed to send request..." << std::endl;
close(socket_desc);
return 0;
}
int n;
std::string raw_site;
while ((n = recv(socket_desc, buffer, sizeof(buffer), 0)) > 0){
raw_site.append(buffer, n);
}
close(socket_desc);
std::cout << raw_site << std::endl;
return 0;
}
|
70,551,359 | 70,552,458 | How to print and modify char in C++ | I want to create a project that will print the '|' character as 4 layers going 1 3 5 7 something like
|
|||
|||||
|||||||
I wrote a for loop for this and the code is here:
for (int i = 1; i <= 4; i++) {
//for loop for displaying space
for (int s = i; s < 4; s++) {
cout << " ";
}
//for loop to display star equal to row number
for (int j = 1; j <= (2 * i - 1); j++) {
cout << "|";
}
// ending line after each row
cout << "\n";
}
So how can I make a code that will take user input like
cout << "Please enter a row number \n" << "Please enter a column number" << endl;
and let say the user entered 2 as row number 2 as column number I want the output to be something like
|
|
|||||
|||||||
Deletes 2 '|' character from the 2nd row
First I think putting every character in a array like char arr[] = { '|' , '||' , '|||', '||||'}
and deleting according to user input but I failed. Any help?
| Here is a solution:
#include <iostream>
#include <vector>
std::size_t getLayerCount( )
{
std::cout << "How many layers to print: ";
std::size_t layerCount { };
std::cin >> layerCount;
return layerCount;
}
std::vector< std::vector<char> > generateShape( const std::size_t layerCount )
{
const std::size_t MAX_CHAR_COUNT_IN_A_ROW { layerCount * 2 };
constexpr char spaceChar { ' ' };
std::vector< std::vector<char> > shape( layerCount, std::vector<char>( MAX_CHAR_COUNT_IN_A_ROW, spaceChar ) );
for ( std::size_t row { }; row < layerCount; ++row )
{
for ( std::size_t offset { layerCount - row - 1 }; offset < layerCount + row; ++offset )
{
shape[ row ][ offset ] = '|';
}
shape[ row ][ MAX_CHAR_COUNT_IN_A_ROW - 1 ] = '\0';
}
return shape;
}
void printShape( const std::vector< std::vector<char> >& shape )
{
for ( const auto& row : shape )
{
std::cout.write( row.data( ), row.size( ) ).write( "\n", 1 );
}
}
void deleteSpecificChars( std::vector< std::vector<char> >& shape )
{
std::cout << "Please enter a row number: ";
std::size_t rowNumber { };
std::cin >> rowNumber;
std::cout << "Please enter a column number: ";
std::size_t colNumber { };
std::cin >> colNumber;
--rowNumber;
--colNumber;
const std::size_t layerCount { shape.size( ) };
const std::size_t posOfFirstCharInRow { layerCount - rowNumber - 1 };
const std::size_t posOfTargetCharInRow { posOfFirstCharInRow + colNumber };
const std::size_t posOfLastCharInRow { posOfFirstCharInRow + ( 2 * rowNumber ) };
for ( std::size_t idx { posOfTargetCharInRow }; idx <= posOfLastCharInRow; ++idx )
{
shape[ rowNumber ][ idx ] = ' ';
}
}
int main( )
{
const std::size_t layerCount { getLayerCount( ) };
std::vector< std::vector<char> > shape { generateShape( layerCount ) };
printShape( shape );
deleteSpecificChars( shape );
printShape( shape );
return 0;
}
Sample input/output:
How many layers to print: 4
|
|||
|||||
|||||||
Please enter a row number: 2
Please enter a column number: 2
|
|
|||||
|||||||
Another one:
How many layers to print: 5
|
|||
|||||
|||||||
|||||||||
Please enter a row number: 4
Please enter a column number: 4
|
|||
|||||
|||
|||||||||
|
70,551,378 | 70,551,577 | Calculate integral using rectangle method in Pascal gives 0 while in C++ good results | I'm trying to implement the rectangle method in Pascal. The point is, I'm getting wrong results. I'm getting 0, while the same code in C++ gives me good results. Why is that? Thanks.
Pascal:
Program HelloWorld(output);
function degrees2radians(x: real) : real;
var
result: real;
begin
result := x * 3.14159 / 180.0;
end;
function fun1(x: real) : real;
var
result: real;
begin
x := degrees2radians(x);
result := Sin(x);
end;
function rect_method(a: real; b: real; n: integer) : real;
var
result: real;
h: real;
integral: real;
i : integer;
begin
integral := 0;
i := 0;
h := (a - b) / n;
for i := 1 to n do
begin
integral := integral + fun1(b + i*h)*h;
end;
result := integral;
end;
var
result: real;
begin
result := rect_method(1.0, -2.0, 3);
writeln('result = ', result);
end.
And C++ (which works: https://onlinegdb.com/ubuNQInB2):
#include <iostream>
#include <cstdlib>
#include <cmath>
double degrees2radians(double x)
{
return x * 3.14159 / 180;
}
double f1(double x)
{
x = degrees2radians(x);
return sin(x);
}
double rectangle_method(double a, double b, int n)
{
float h, integral = 0;
h = (a - b) / (double) n;
for (int i=1; i<=n; i++)
integral += f1(b + i*h)*h;
return integral;
}
int main()
{
std::cout << rectangle_method(1, -2, 3) << "\n";
return 0;
}
| In your Pascal code result is a local variable, which has nothing to do with the special identifier called result that you want to use:
function degrees2radians(x: real) : real;
var
result: real;
begin
result := x * 3.14159 / 180.0;
end;
You should remove result: real; in all your functions.
However, "fixed" code produces zero anyway: https://onlinegdb.com/_M2pGk134, which is actually correct. That is, this code should return zero.
I rewrote this code in Julia (the language doesn't matter, the point is that it supports high-precision floating-point types out of the box; BigFloat is such a high-precision float), and the result is still zero:
degrees2radians(x::Real)::Real = x * 3.14159 / 180
f1(x::Real) = sin(degrees2radians(x))
function rectangle_method(a::Real, b::Real, n::Integer)
integral = 0
h = (a - b) / n;
for i in 1:n
@show i f1(b + i*h)*h
integral += f1(b + i*h)*h;
end
return integral;
end
@show rectangle_method(BigFloat("1"), -BigFloat("2"), 3)
The output looks like this:
i = 1
f1(b + i * h) * h = -0.01745239169736329549313317881927049082689975241899824937795751704833664190229729
i = 2
f1(b + i * h) * h = 0.0
i = 3
f1(b + i * h) * h = 0.01745239169736329549313317881927049082689975241899824937795751704833664190229729
rectangle_method(BigFloat("1"), -(BigFloat("2")), 3) = 0.0
So, f1(b + 2 * h) * h is zero, and f1(b + 1 * h) * h is exactly (look at the amount of digits after the decimal point!) the negative of f1(b + 3 * h) * h, so they cancel out in the integral sum, resulting in zero.
|
70,551,699 | 70,551,743 | Use of std::move in std::accumulate | In my Fedora 34 environment (g++), std::accumulate is defined as:
template<typename ITER, typename T>
constexpr inline T accumulate(ITER first, ITER last, T init)
{
for (; first != last; ++first)
init = std::move(init) + *first; // why move ?
return init;
}
If the expression init + *first is already an rvalue, what is the purpose of std::move ?
| std::move(init) + *first can sometimes generate more efficient code than init + *first, because it allows init to be overwritten. However, since (as you observed) the result of the + will generally be an rvalue, there is no need to wrap the entire expression in a second std::move.
For example, if you are accumulating std::strings, then std::move(init) + *first might be able to append *first into reserved-but-not-yet-used space in init's buffer instead of having to allocate a new buffer whose length is the sum of the lengths of init and *first.
|
70,551,736 | 70,552,115 | Problem in My Merge Sort Implementation C++ | I've been learning about the merge sort algorithm, and I am having a bit of trouble. In my implementation, some of the numbers in the output are missing and others are repeated. I'm using vectors and following the algorithm described in Introduction to Algorithms by Cormen et. al. and Geeksforgeeks.
Here's the code:
#include <iostream>
#include <vector>
using namespace std;
void merge_sort(vector<int>&, int, int);
void merge(vector<int>&, int, int, int);
int main() {
vector<int> A = {5, 2, 4, 6, 1, 3};
int p = 0;
int r = A.size() - 1;
merge_sort(A, p, r);
for(int num : A)
cout << num << " ";
return 0;
}
void merge_sort(vector<int>&A, int p, int r){
if(p >= r)
return;
int mid = (p+r)/2;
merge_sort(A, p, mid);
merge_sort(A, mid+1, r);
merge(A, p, mid, r);
}
void merge(vector<int>&A, int p, int mid, int r){
int numLeft = mid - p + 1;
int numRight = r - mid;
//create two new vectors
vector<int> left;
vector<int> right;
//copy elements over
for(int i = 0; i < numLeft; i++)
left.push_back(A[i]);
for(int j = mid+1; j < (mid+1+numRight); j++)
right.push_back(A[j]);
//compare elements from the two arrays
int i = 0;
int j = 0;
int k = 0;
while(i < numLeft && j < numRight){
if(left[i] <= right[j]){
A[k] = left[i];
i++;
}
else{
A[k] = right[j];
j++;
}
k++;
}
//check if one half terminated before the other
while(i < numLeft){
A[k] = left[i];
k++; i++;
}
while(j < numRight){
A[k] = right[j];
k++; j++;
}
}
Output: 1 2 3 6 1 3
| Your merge function assumes that you are sorting with p=0. You should copy from p, not from 0. Then put back with k starting from p:
//copy elements over
for (int i = p; i < p + numLeft; i++)
left.push_back(A[i]);
for (int j = mid + 1; j < (mid + 1 + numRight); j++)
right.push_back(A[j]);
//compare elements from the two arrays
int i = 0;
int j = 0;
int k = p;
|
70,551,862 | 70,552,027 | pybind11 c++ unordered_map 10x slower than python dict? | I exposed a c++ unordered_map<string, int> to python, and it turned out this map is 10x slower than python's dict.
See code below.
// map.cpp file
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <string>
#include <unordered_map>
namespace py = pybind11;
PYBIND11_MAKE_OPAQUE(std::unordered_map<std::string, int>);
PYBIND11_MODULE(map, m) {
// map
py::bind_map<std::unordered_map<std::string, int>>(m, "MapStr2Int");
}
On MacOS, compile it with this cmd:
c++ -O3 -std=c++14 -shared -fPIC -Wl,-undefined,dynamic_lookup $(python3 -m pybind11 --includes) map.cpp -o map$(python3-config --extension-suffix)
Finally, compare with python dict in ipython:
In [20]: import map
In [21]: c_dict = map.MapStr2Int()
In [22]: for i in range(100000):
...: c_dict[str(i)] = i
...:
In [23]: py_dict = {w:i for w,i in c_dict.items()}
In [24]: arr = [str(i) for i in np.random.randint(0,100000, 100)]
In [25]: %timeit [c_dict[w] for w in arr]
59 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [26]: %timeit [py_dict[w] for w in arr]
6.58 µs ± 87.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
As seen, c_dict is much much slower than python version py_dict.
Why and how to improve?
| You are comparing a native dictionary implementation (the one from the Python Standard Library) and a pybind wrapped one. I would bet a coin that a C++ program directly using std::unordered_map is certainly faster than the equivalent one, written in Python and using a dict.
But it is not what you are doing here. Instead of that, you ask pybind to generate a wrapper that will convert Python types into C++ ones, call the C++ standard library class methods and then convert back the result into a Python type. Those convertions are likely to require allocation and deallocation and will indeed take some time. Moreover, pybind is a very clever (hence complex) tool. You cannot expect it to generate code that would be as much optimized as direct calls using the Python API.
Unless you intend to use a specially optimized algorithm for the hashing function, you will not be able to write a C or C++ code that will be faster than the standard library, because the builtin types are already coded in C language. At most, you should be able to be as fast as the standard library if you mimic it and directly use the Python/C API.
|
70,551,870 | 70,552,105 | How i can utilize S(*)(int)? | For educational reasons, I'm studying the C++ language using clang-12 std=c++17
And I have the following code:
Fullcode
#include <cstdio>
#include <iostream>
#include <type_traits>
using namespace std;
struct S {
void operator()(int) {}
};
int main()
{
S(*d)(int);
//d = whatValue??
return 0;
}
I'm studying the types of variables that exist in the C++ language, and I came across this situation above.
What value can I assign to the d variable?
Could it be a language bug? I've already researched several topics on stackoverflow and cppreference and haven't found any way to initialize this variable S(*d)(int) .
| The variable d is a pointer to a function taking an int as argument and returning an S. Note that it cannot point to non-static member functions. You could, e.g., use it like this:
struct S {
void operator()(int) {}
};
S f(int) { return S(); }
int main()
{
S(*d)(int) = &f;
S rc = d(17);
}
As functions decay to pointer types, you can actually leave the & out. The same isn't true for non-static member functions, though. If you wanted to get a pointer to a member function of S taking an int as argument and returning void (your operator() returns void not S) you'd need to use the &:
int main() {
void (S::*d)(int) = &S::operator();
S obj;
S rc = (obj.*d)(17); // use d
}
Pointer to member functions are different to pointer to functions because they have an implicit first argument: the this pointer. With C++ it is quite rare that pointer to functions are used for other reasons than interfacing C code: using std::function<void(int)> is more flexible, although also type-erase and most likely involving a virtual function call and not being inlinable. If the function can be a function template it is common to pass function objects which are std::invoke()ed (instead of directly called) which support function pointers, pointer to member functions, pointer to non-function members, lambdas, functions, etc.
|
70,551,980 | 70,552,193 | ctypes return array of strings std::vector<std::string>> | I am able to return a string after it is converted to a char*.
import ctypes
from subprocess import Popen, PIPE
# Press the green button in the gutter to run the script.
libname = "c:\temp\debug_api_lib.dll"
c_lib = ctypes.windll.LoadLibrary(libname)
class Gilad(object):
def __init__(self, host, port):
c_lib.menu_function_new.argtypes = [ctypes.c_char_p, ctypes.c_int]
c_lib.menu_function_new.restype = ctypes.c_void_p
c_lib.get_mac_address_new.argtypes = [ctypes.c_void_p]
c_lib.get_mac_address_new.restype = ctypes.c_char_p
c_lib.get_otp_data_new.argtypes = [ctypes.c_void_p]
c_lib.get_otp_data_new.restype = (ctypes.c_char_p * 3)
self.obj = c_lib.menu_function_new(host, port)
def get_mac_address(self):
return c_lib.get_mac_address_new(self.obj)
def get_otp_data(self):
return c_lib.get_otp_data_new(self.obj)
if __name__ == '__main__':
host = "11.11.11.11".encode('utf-8')
t = Gilad(host, 21)
print(t.get_mac_address())
otp_data: object = t.get_otp_data()
for i in otp_data: //the issue is here
print(i)
Here is my cpp code wrapped with c-style:
extern "C"
{
__declspec(dllexport) menu_function* menu_function_new(char * host, int port)
{
return new menu_function(host, port);
}
__declspec(dllexport) char* get_mac_address_new(menu_function* menu_function)
{
std::string res_string = menu_function->get_mac_address();
char* res = new char[res_string.size()];
res_string.copy(res, res_string.size(), 0);
res[res_string.size()] = '\0';
return res;
}
__declspec(dllexport) char** get_otp_data_new(menu_function* menu_function)
{
int num = 3;
std::vector<std::string> res_string = menu_function->get_otp_data();
char** res = (char**)malloc(num * sizeof(char**));
for (int i = 0; i < num; i++)
{
res[i] = (char*)malloc(res_string[i].size());
res_string[i].copy(res[i], res_string[i].size(), 0);
res[i][res_string[i].size()] = '\0';
}
return res;
}
I can see in res the 3 strings being copied correctly, but when printing in python I get: b'\xa0y\xa4P\x12\x01'
I guess I am printing the pointers.
| The function is returning a char**, and you've told Python that it is returning a char*[3] (an array of 3 char* pointers, not a pointer itself), so the returned value isn't being interpreted properly by ctypes.
Change the return type to ctypes.POINTER(ctypes.c_char_p), or alternatively change your program to return something that has the same size as char*[3], like std::array<char*, 3> or struct otp_data { char *one, *two, *three; }; (which would be 1 less malloc since you can return this by value)
|
70,552,086 | 70,552,228 | Fixing bug in removing duplicates from sorted linked list | I'm trying to remove duplicates from a sorted linked list. I have written the algorithm but still missing a core bug logic that I can't trace.
Consider the list
1->2->3->3->4->4->5
Output should be 1 - > 2 - > 5
The program works fine for a simple case, like 1>2>2>3, but for multiple duplicates like 1>2>2>3>3>5 it outputs 1>3>5
Here is a complete program:
struct Node
{
Node* next;
int val;
Node()
{
}
};
int main()
{
Node* n1 = new Node();
n1->val = 1;
Node* n2 = new Node();
n2->val = 2;
n1->next = n2;
Node* n3 = new Node();
n3->val = 3;
n2->next = n3;
Node* n4 = new Node();
n4->val = 3;
n3->next = n4;
Node* n5 = new Node();
n5->val = 4;
n4->next = n5;
Node* n6 = new Node();
n6->val = 4;
n5->next = n6;
Node* n7 = new Node();
n7->val = 5;
n6->next = n7;
n7->next = nullptr;
Node* fast = n1->next;
Node* slow = n1;
Node* temp = n1;
Node* prevSlow = nullptr;
while (slow != nullptr && fast != nullptr)
{
if (fast->val == slow->val)
{
prevSlow->next = fast->next;
fast = fast->next;
slow->next = prevSlow->next;
}
else {
prevSlow = slow;
slow = slow->next;
fast = fast->next;
}
}
}
| For starters this constructor
Node()
{
}
does not make a sense. Remove it.
The statement
prevSlow->next = fast->next;
in this if statement
if (fast->val == slow->val)
{
prevSlow->next = fast->next;
fast = fast->next;
slow->next = prevSlow->next;
}
in general can invoke undefined behavior because initially the pointer prevSlow is set to nullptr
Node* prevSlow = nullptr;
Pay attention to that the node n1 is the head node of the list. It can be changed in the process of removing duplicates. Also you need to free memory of removed nodes.
The algorithm can be implemented the following way
auto is_duplicate = [] ( const Node *node )
{
return node->next != nullptr && node->val == node->next->val;
};
for ( Node **current = &n1; *current != nullptr; )
{
if ( is_duplicate( *current ) )
{
do
{
Node *tmp = *current;
*current = ( *current )->next;
delete tmp;
} while ( is_duplicate( *current ) );
Node *tmp = *current;
*current = ( *current )->next;
delete tmp;
}
else
{
current = &( *current )->next;
}
}
|
70,552,114 | 70,552,160 | Makefile giving error with No target for rule G++ | Complete Makefile noob here. I cannot figure out why this is happening, but I think it is whitespace/tab. I have this Makefile:
BUILD_DIR = build/debug
CC = g++
SRC_FILES = $(wildcard $(SRC_DIR)/*.cpp)
OBJ_NAME = play
INCLUDE_PATHS = -Iinclude
LIBRARY_PATHS = -Llib
COMPILER_FLAGS = -std=c++11 -Wall -O0 -g
LINKER_FLAGS = -lsdl2
all: $(CC) $(COMPILER_FLAGS) $(LINKER_FLAGS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(SRC_FILES) -o $(BUILD_DIR)/$(OBJ_NAME)
and it gives this error:
make: *** No rule to make target `g++', needed by `all'. Stop.
If I move the string to the bottom with tab and just use all: on one line and the string on the other it gives this:
Makefile:12: *** missing separator. Stop.
And I thought Python was crazy about space. Cannot figure out what I am doing wrong.
| You need to put commands on a new line:
all:
$(CC) $(COMPILER_FLAGS) $(LINKER_FLAGS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(SRC_FILES) -o $(BUILD_DIR)/$(OBJ_NAME)
and make sure it is indented with tab, not space
It is also not python, it's make
You couuld also use a semicolon to separate dependencies from commands like this:
all: $(SRC_FILES); $(CC) $(COMPILER_FLAGS) $(LINKER_FLAGS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(SRC_FILES) -o $(BUILD_DIR)/$(OBJ_NAME)
|
70,552,547 | 70,552,742 | g++ boost iostreams zlib linking | I compiled boost iostreams with zlib and bzip2 support according to this tutorial https://www.boost.org/doc/libs/1_49_0/libs/iostreams/doc/installation.html :
I changed working directory to ~/cpp_libs/boost_code/boost_1_55_0/libs/iostreams/build/ and typed:
bjam -s ZLIB_SOURCE=~/cpp_libs/zlib_code/zlib-1.2.11 -s BZIP2_Source=~/cpp_libs/bzip2_code/bzip2
It has generated libs:
~/cpp_libs/boost_code/boost_1_55_0/bin.v2/standalone/zlib/gcc-9/debug/libboost_zlib.so.1.55.0
~/cpp_libs/boost_code/boost_1_55_0/bin.v2/libs/iostreams/build/bzip2/gcc-9/debug/libboost_bzip2.so.1.55.0
~/cpp_libs/boost_code/boost_1_55_0/bin.v2/libs/iostreams/build/gcc-9/debug/libboost_iostreams.so.1.55.0
However now I don't know how to link to this libraries, because it has version extensions in their names.
If I rename libraries:
libboost_zlib.so.1.55.0 to libboost_zlib.so
libboost_bzip2.so.1.55.0 to libboost_bzip2.so
libboost_iostreams.so.1.55.0 to libboost_iostreams.so
I can link them with command "-lboost_zlib -lboost_iostreams -lboost_bzip2", however when I run the compiled program it prints:
./main: error while loading shared libraries: libboost_iostreams.so.1.55.0: connot open shared object file: No such file or directory.
So how to link to this libraries without renaming?
I am using g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
| Here's the usual workflow that's used to build and install shared libraries on Linux. The exact details vary widely between different libraries and all packages but they all follow the same general framework:
The software package builds an installation image, placing the libraries as <libdir>/<name>.<version>, where <libdir> is the system library installation directory, like /usr/lib or /usr/lib64, or perhaps /lib or /lib64, or there could be several variations.
<name> is the base name of the shared library, such as libboost_zlib.so in your case, and is the epoch/version/release of the shared library, or 1.55.0.
As part of building the shared library, the library's name, epoch and version is recorded in the shared library itself, in this case it would be libboost_zlib.so.1.55.
At this point the actual details start to diverge between different Linux distributions. In some this step occurs as part of creating an installation package. On other Linux distributions this happens when the package actually gets installed, but at some point the ldconfig tool gets executed.
ldconfig goes through and creates all the needed symbolic links for all shared libraries in standard system shared library directories. In this case it would create the following symbolic links:
libboost_zlib.so => libboost_zlib.so.1.55
libboost_zlib.so.1.55 => libboost_zlib.so.55.0
This ends up being the final state of the installed shared library. When you build the software with the shared library the -lboost_zlib flag to the linker results in the linker attempting to link the executable with libboost_zlib.so. This reads the libboost_zlib.so.1.55 encoded in the actual shared library (see step 3 above), and the linked executable is marked as requiring libboost_zlib.so.1.55 to be loaded when it gets executed.
When the linked executable gets executed, an attempt is made to open libboost_zlib.so.1.55, which uses that symbolic link to find the actual shared library.
I changed working directory to
~/cpp_libs/boost_code/boost_1_55_0/libs/iostreams/build/ and typed:
bjam -s ZLIB_SOURCE=~/cpp_libs/zlib_code/zlib-1.2.11 ...
You used a non-standard process for compiling and building these shared libraries. It's now up to you to fill in the missing steps, do all the heavy lifting, and create the missing symbolic links. Note that you can commandeer ldconfig into doing your bidding, by pointing it at your installation directory, see its manual page for more information.
You will also need to deal with the fact that the shared libraries ended up getting installed in a non-standard directory that the runtime loader will not search by default. You will need to use additional compilation options (namely -rpath) when linking code with the shared libraries in that directory, but that's going to be a separate issue.
|
70,553,335 | 70,553,995 | VSCode Include path C++ | I am trying to learn C++, but I am having trouble. When trying to compile my source file, I receive the below error message for all of my header files.
I have tried adding multiple paths to my CPP properties file but am still having trouble identifying the problem.
Above is the properties file I previously mentioned.
Also, here is how my directory is set up. Any help is appreciated.
| So as far as I am able to understand, you are trying to run main.cpp that has a user defined header file Book.h
But Book.h is in another directory so, try using
#include "../headers/Book.h"
Basically you need to give the location of Book.h file in respect to main.cpp
|
70,553,401 | 70,553,445 | Passing new value to a pointer via a recursive function in c++ | How I can change the value of p to 1 passing it as an argument to a recursive function.
This is my code:
class Solution
{
void g(int n,int k,int *p){
if(k==0) return;
if(k%n==0) g(n,k-1,1);
cout<<p<< endl;
g(n,k-1,p+1);
}
public:
int josephus(int n, int k)
{ int p=1;
g(n,k,&p);
return p;
}
};
I get this errors:
prog.cpp: In member function void Solution::g(int, int, int*):
prog.cpp:14:21: error: invalid conversion from int to int* [-fpermissive]
if(k%n==0) g(n,k-1,1);
^
prog.cpp:12:9: note: initializing argument 3 of void Solution::g(int, int, int*)
void g(int n,int k,int *p){
| The error says you cannot pass an int as a parameter to a function when it expects an int *.
There is also a logical bug in your code:
g(n,k-1,p+1);
This recursive call increments the pointer value, which makes it point past the passed in object, since the function was called like this:
{ int p=1;
g(n,k,&p);
Since your function takes an int *, you need to dereference the pointer to manipulate the referenced object. So, you probably intend to increment *p and then make the recursive call:
++*p;
g(n,k-1,p);
To address the compilation error, you probably intended to assign 1 to the int object and make the recursive call.
if(k%n==0) {
*p = 1;
g(n,k-1,p);
}
|
70,553,678 | 70,554,061 | Is there a shorter way to calculate if (a == b || a == c) in C++ | I am wondering if in c++11 you can calculate this:
if (a == b || a == c) {
// do something
}
In a much shorter and more concise way such as something like this:
if (a == (b || c)) {
// do something
}
(I know that the above code would not work [it would calculate if b or c and then check if the result is equal to a]. I am wondering if there is a similar way to implement the code before: if (a == b || a == c) {})
| What you are basically doing is testing if a equals a value in a set. And yes std::set can be used but its slow. This example is a bit slower then hard coding the full expression. But it shows what is being calculated and the righthand side will look like a set/collection.
#include <utility> // for std::size_t
template<typename type_t, std::size_t N>
inline constexpr bool is_any_of(const type_t& lhs, const type_t(&set)[N])
{
for (const auto& rhs : set)
{
if (lhs == rhs) return true;
}
return false;
}
int main()
{
constexpr int a = 1;
constexpr int b = 3;
constexpr int c = 2;
constexpr int d = 1;
static_assert(!is_any_of(a, { b, c }));
static_assert(is_any_of(a, { b, d }));
static_assert(is_any_of(a, { b, c, d }));
return 0;
}
|
70,553,735 | 70,554,906 | How to draw a perfect 3D Spring using Cylinders | I am trying to draw a Spring using only Cylinders.
void spring(GLfloat rounds, GLfloat height, GLfloat thickness, GLfloat radius) {
glColor3f(1.0, 1.0, 1.0);
GLfloat j = 0;
for (GLfloat i = 0; i <= rounds * 360; i += 5) {
glPushMatrix();
glRotatef(i, 0, 1, 0);
glTranslatef(0, j, radius);
gluCylinder(qobj, thickness, thickness, radius, 50, 50);
glPopMatrix();
j += height / (rounds * 360);
}
}
spring(4, 2.5, 0.03, 0.1);
The spring drawn with this code is not perfect. Also, when the radius is increased the shape of the spring is distorted.
How can I fix this ?
| A spring is a shape that is curved in 3 dimensions. Cylinders cannot be sticked together perfectly to form a spring. Why don't you create your own mesh with the OpenGL primitives?
e.g.: Use a TRINGLESTRIP to wrap a long ribbon around a tube that is bent into a spring:
#include <vector>
#include <algorithm>
void createSpring(
GLfloat rounds, GLfloat height, GLfloat thickness, GLfloat radius,
std::vector<GLfloat> &vertices, std::vector<GLuint> &indices)
{
const int slices = 32;
const int step = 5;
for (int i = -slices; i <= rounds * 360 + step; i += step)
{
for (int j = 0; j < slices; j ++)
{
GLfloat t = (GLfloat)i / 360 + (GLfloat)j / slices * step / 360;
t = std::max(0.0f, std::min(rounds, t));
GLfloat a1 = t * M_PI * 2;
GLfloat a2 = (GLfloat)j / slices * M_PI * 2;
GLfloat d = radius + thickness * cos(a2);
vertices.push_back(d * cos(a1));
vertices.push_back(d * sin(a1));
vertices.push_back(thickness * sin(a2) + height * t / rounds);
}
}
for (GLuint i = 0; i < (GLuint)vertices.size() / 3 - slices; ++i)
{
indices.push_back(i);
indices.push_back(i + slices);
}
}
void drawSpring(
const std::vector<GLfloat>& vertices, const std::vector<GLuint>& indices)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // just to see the mesh (delete later)
glColor4f(1, 1, 1, 1);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices.data());
glDrawElements(GL_TRIANGLE_STRIP, indices.size(), GL_UNSIGNED_INT, indices.data());
glDisableClientState(GL_VERTEX_ARRAY);
}
std::vector<GLfloat> springVertices;
std::vector<GLuint> springIndices;
void init()
{
createSpring(1.5, 0.25, 0.03, 0.1, springVertices, springIndices);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(20.0, 1.0f, 0.1f, 1000);
glMatrixMode(GL_MODELVIEW);
gluLookAt(0, -1, 0.125, 0, 0.0, 0.125, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawSpring(springVertices, springIndices);
glutPostRedisplay();
glutSwapBuffers();
}
|
70,554,169 | 70,554,353 | Concept subsumption working for functions, but not for structs | Apologies for potentially wrong title, that is my best guess what is happening.
I was learning some basic concepts and tried this:
#include <concepts>
#include <iostream>
#include <memory>
template<typename T>
concept eight = sizeof(T) == 8;
template<typename T>
concept basic = std::is_trivial_v<T>;
template<typename T>
requires eight<T>
constexpr void ff(){
std::cout << "eight" << std::endl;
}
template<typename T>
requires eight<T> && basic<T>
constexpr void ff(){
std::cout << "eight and basic" << std::endl;
}
template<typename T>
requires eight<T>
struct ffs{
};
template<typename T>
requires eight<T> && basic<T>
struct ffs{
};
What is insane to me is that I get error for struct when same stuff works for functions.
:29:10: error: requires clause differs in template
redeclaration requires eight && basic
^ :24:10: note: previous template declaration is here requires eight
It could be that I am just UB+NDRing in both cases but compiler does not mind in first case(not that when I remove structs from code my code seems to run as expected, including distinguishing properly what to invoke based on concepts), but that seems unlikely.
P.S. if somebody wonders why I just don't use requires instead of trivial concepts here is the answer.
| Overloading template classes wasn't allowed before concepts, and it still not allowed even with concepts. Use partial specialization:
template <typename T>
requires eight<T>
struct ffs {};
template <typename T>
requires basic<T>
struct ffs<T> {};
Or with the terse syntax:
template <eight T>
struct ffs {};
template <basic T>
struct ffs<T> {};
Note that in both cases, the constraints on the primary template automatically apply to all specializations.
|
70,554,475 | 70,554,494 | const pointer and pointer to const value as parameter | I have a program like below and expect that:
with function void myFunc1 ( const int *x) ==> I cannot change the value of at the memory location that x points to, but can change the memory location that x points to.
with function void myFunc2 ( int const *x) ==> I cannot change the location that x points to as it is a const pointer. But I could change the value at the memory location that x points to.
However, upon compiling the code, I don't see the difference between const int *x vs int const *x:
in both function, the lines *x=8 in both function return error. I didn't expect error from myFunc2 because it is a const pointer, not a pointer to a const value.
in myFunc1, I expected to see value 5 after myFunc1 is close.
Could the experts here explain my 2 unexpected results above ? Here is my code:
#include "stdio.h"
int a = 5; // declared a global,
void myFunc1 ( const int *x) { // const parameter: pointer to a const int value.
// *x= 8; // error: assignment of read-only location ‘* x’ ==> cannot change the value at the location pointed by pointer. This is expected
printf("%d \n ", *x);
x = &a; // can change where the pointer point to.
// a is global and is not loss after closing myFunc2
printf("value in myFunc1: %d \n ", *x);
}
void myFunc2 ( int const *x) { // const parameter: const pointer, cannot change the address that x points to.
// *x= 8; // error: assignment of read-only location ‘* x’
printf("%d \n ", *x);
x = &a; // no compiling error here. This is not expected.
printf("value in myFunc2: %d \n ", *x);
}
int main() {
int *y;
int z = 6;
y = &z;
printf("value before myFunc1: %d \n", *y);
myFunc1(y);
printf("value after myFunc1: %d \n", *y); // expect to print 5. Result: print 6.
printf("value before myFunc2: %d \n", *y);
myFunc2(y);
printf("value after myFunc2: %d \n", *y); // expect to print 8 if the line *x=8 could be compiled . Result: print 6.
return 1;
}
|
I don't see the different between having 2 parameters (const int *x) vs (int const *x):
That's because int const* and const int* are the same thing.
If you want to make the pointer const, you have to put a const on its right, like this: int * const, a constant pointer to (non-constant) integer.
Unrelated (is it?) note on East const
I am one of those in favour of the so called East const, which means I prefer writing the const always on the right of what it applies to. For instance,
for a "pointer to constant int", I write int const *,
for a "constant pointer to constant int", I write int const * const.
As you see, the sentences in quotes map to the types if you read them right-to-left:
// 1 2 3 4 4 3 2 1
int const * const // constant pointer to constant int
Furthermore, always thinking of const as something that can be put on the right of what it applies to has also other advantages, sometimes in terms of peculiarities of the language that you can discover.
For instance, the following is how I discovered something more about references.
Take the declaration of a function parameter taken by reference to constant: int const& p. If you write it like this and think of it the East const way, it is clear that it declaring a p which is a reference to a constant int, not a constant reference to int.
After all, thinking East const, what would a constant reference to int look like? It'd be int & const, with the const on the right of what we'd like it to apply to, the reference &. However, this syntax is incorrect.
Why is that? Why can't I make a reference constant? Because it always is, as references cannot rebind. The standard simply doesn't let you write something totally redundant as a const applied to a reference.
|
70,554,489 | 70,554,505 | What special member function is used for copy initialization in c++? | I'm testing c++ class initialization.
class Point
{
private:
int x,y;
public:
Point() = delete;
Point(int a):x(a), y(0) { std::cout << "Conversion" << std::endl;}
Point(const Point&) { std::cout << "Copy constructor" << std::endl;}
//Point(const Point&) = delete;
Point& operator=(const Point&) = delete;
Point(Point&&) = delete;
Point& operator=(Point&&) = delete;
};
int main()
{
Point p1(5); //case1
Point p2 = 5; //case2
return 0;
}
In the above code, I thought "5" will be converted to a temp object by conversion constructor for both case1/2 at first. And then, I expected that copy constructor must be used for initializing of p1 & p2. But, it was not.
When I run this code, I saw just two "Conversion" message in console. No "Copy Constructor" message.
Even though, I deleted all copy constructor, move constructor, copy assignment operator and move assignment operator, this code worked well.
I would appreciate if you let me know what special member function will be used for initializing after creating temp object for "5",
I am using g++ compiler with std=c++17 option.
| Case I
In case 1 the converting constructor is used since you have provided a constructor that can convert an int to Point. This is why this constructor is called converting constructor.
Case II
From mandatory copy elison
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:
In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type.
In case 2, even if you delete copy/move constructor only the converting constructor will be used. This is due to mandatory copy elison(in C++17) as quoted above.
|
70,554,765 | 70,560,542 | Why the breakpoints set in STL are "skipped/ignored" while using LLDB? | My goal is: I want to step into the some line of code of STL istream. So I used custom built "LIBC++13" with "Debug" build type(the command I used are shown at the bottom), so that (I think) I can get a fully debuggable version of STL, and be able to step into everything I want. But I got a problem.
Here are my breakpoints settings for istream, BREAKPOINT A(Line 1447) and want to step into Line 310:
// -*- C++ -*-
//===--------------------------- istream ----------------------------------===//
// ..................(other).....................
basic_istream<_CharT, _Traits>&
operator>>(basic_istream<_CharT, _Traits>& __is,
basic_string<_CharT, _Traits, _Allocator>& __str)
{
ios_base::iostate __state = ios_base::goodbit;
typename basic_istream<_CharT, _Traits>::sentry __sen(__is); // BREAKPOINT A (Line 1447)
if (__sen) // Line 1448
{
// ...
}
// ..................(other).....................
template <class _CharT, class _Traits>
basic_istream<_CharT, _Traits>::sentry::sentry(basic_istream<_CharT, _Traits>& __is,
bool __noskipws)
: __ok_(false)
{
if (__is.good()) // Want To Step Into Here (Line 310)
{
// ...
}
and the program:
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream ifs{"testdata.txt"};
string tmp{};
ifs >> tmp;
}
My problem is: With GDB, when I stopped at "BREAKPOINT A", I can step into "Line 310". But with LLDB, when I stopped at "BREAKPOINT A", I cannot step into "Line 310", and trying to step into would cause execution stopping at "Line 1448", which just skipping the "Line 310". Why was that? And Moreover, either with LLDB or GBD, I just cannot explicitly set breakpoint at "Line 310". Have no idea what happened in my situation.
So my question is: Why some lines of code in STL will be skipped/ignored by LLDB? (in my case, that is Line 310)
LIBC++13 is built by command: (using the examples in Building Libcxx Guides, /usr/local/myllvm is my install location))
cmake -G Ninja -S llvm -B build \
-DLLVM_ENABLE_PROJECTS="libcxx;libcxxabi" \
-DCMAKE_BUILD_TYPE="Debug" \
-DCMAKE_INSTALL_PREFIX="/usr/local/myllvm" \
-DCMAKE_CXX_COMPILER="clang++"
Program is compiled with recommended options:
clang++ -nostdinc++ -nostdlib++ \
-isystem /usr/local/myllvm/include/c++/v1 \
-L /usr/local/myllvm/lib \
-Wl,-rpath,/usr/local/myllvm/lib \
-lc++ -g -O0 test1.cpp
| By default, lldb treats functions in the std::: namespace the same way as functions without debug information, and auto-steps back out instead of stopping in the function.
For most users, the fact that you have source information for inlined stl functions is more an accident of the implementation than an indication of interest in those functions; and stepping into STL function bodies is disruptive and not helpful.
This behavior is controlled by the lldb setting target.process.thread.step-avoid-regex - if lldb steps into a function that matches this regex, lldb will auto-step out again. The default value is:
(lldb) settings show target.process.thread.step-avoid-regexp
target.process.thread.step-avoid-regexp (regex) = ^std::
If you do need to step into STL functions, just run:
(lldb) settings clear target.process.thread.step-avoid-regexp
and then lldb will stop in stl functions for which you have source information.
|
70,555,169 | 70,555,206 | Unable to read the entire file correctly using fseek() and fread() | I have a file with shader source which i want to read that looks like this:
#version 460 core
layout(location = 0) in vec2 pos;
layout(location = 1) in vec3 color;
layout(location = 0) out vec3 fragColor;
uniform float rand;
out gl_PerVertex
{
vec4 gl_Position;
float gl_PointSize;
float gl_ClipDistance[];
};
void main()
{
fragColor = color * rand;
gl_Position = vec4(pos.x + 0.5 * gl_InstanceID, pos.y, 0, 1);
}
first i find out the size of my file:
fseek(m_file, 0L, SEEK_END);
size_t size = ftell(m_file);
This returns 364. The problem is that if i just copy+paste the file content into a R"()" string and get a strlen it returns 347.
After getting file size i try reading the whole file:
fseek(m_file, 0, SEEK_SET);
size_t count = fread(buffer, 1, size, m_file);
where buffer is allocated with 364 bytes. But fread returns 347 and feof(m_file) returns true. So as a result i get this:
(File explorer also shows that the file size is 364).
However, when i read the same file into a string using std::ifstream, everything works properly:
std::ifstream ifs(filename);
std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
auto size = content.size();
and size is equal to 347.
The question is: am i doing something wrong or Windows/fseek just show the file size wrongly?
| The difference between the two sizes is 19 which coincidencally is the number of lines in your shader.
My guess is this has something to do with line ending conversations. Open the file as binary and the discrepency should go away.
|
70,555,320 | 70,555,925 | Store function inputs for threads | Im trying to make a job system with a similar feature as std::thread where you can pass in parameters in a lambda which get captured e.g ( std::thread([&](int index){...} ), 5) )
This is the entire thread class
#include <condition_variable>
#include <functional>
#include <thread>
using uint = unsigned int;
class Thread {
public:
Thread() {
Start();
}
virtual ~Thread() {
Shutdown();
}
void Start() {
m_Thread = std::thread(&Thread::Poll, this);
}
void Poll() {
{
std::unique_lock<std::mutex> lock(m_Mutex);
m_Condition.wait(lock, [this]()
{
return !m_Jobs.empty() && !m_Stop;
});
m_Job = m_Jobs.front();
m_Jobs.pop_back();
}
m_Job(); // function<void()> type
}
void Execute(std::function<void()> New_Job) {
{ std::unique_lock<std::mutex> lock(m_Mutex);
m_Jobs.push_back(New_Job);
}
m_Condition.notify_one();
}
template <typename Func, typename... Args>
void ExecuteParams(Func f, Args... args) {
Execute(std::bind(f, args...));
}
void Wait() {
while (!m_Jobs.empty() && !m_Stop) {
Poll();
}
}
void Shutdown() {
{
std::unique_lock<std::mutex> lock(m_Mutex);
m_Stop = true;
}
m_Condition.notify_all();
m_Thread.join();
}
std::thread m_Thread;
std::mutex m_Mutex;
std::condition_variable m_Condition;
bool m_Stop = false;
std::function<void()> m_Job;
std::vector<std::function<void()>> m_Jobs;
};
This currently works sort of but if i pass in an index from a for loop for example, the index will just stay 0 for each job...
for(uint i = 0; i < 5; i++) {
MainThread.ExecuteParams([&](uint test)
{
std::unique_lock<std::mutex> L(lock);
std::cout << "executing on thread " << std::this_thread::get_id() << std::endl;
std::cout << test << std::endl;
}, i);
}
| You have a very funny problem introduced :-)
m_Job = m_Jobs.front();
m_Jobs.pop_back();
You always pick the FIRST element to execute, but remove the last one. The result is, that you always execute the first element. I expect, that is not what you want! And as your loop inserts with 0 first, it looks like the var is not stored correctly, but it is. If you run your loop from 10..20 you will always see 10 instead.
BTW: You execute a lot of times your vector without locking the mutex. For example:
void Wait() {
while (!m_Jobs.empty() && !m_Stop) {
...
If you compile with -fsanitize=thread you get a long list of warnings.
|
70,555,805 | 70,556,547 | C++ code don't have errors but not giving output | I am writing code for selection sort in c++. It gives no error when i compile it with the command g++ main.cpp -o main in powershell but when i run the code with ./main, it don't show anything. I tried with hello world program and it worked. I don't know why the selection sort code not working.
Here Is the code of Selection sort
#include<iostream>
using namespace std;
int main()
{
int n, a[n];
cout << "Enter the size of the array = ";
cin >> n;
cout << "Enter the numbers :" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
for (int i = 0; i < n-1; i++)
{
for (int j = i+1; j < n; j++)
{
if (a[i] > a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int b=0; b<n; b++)
{
cout<<a[b];
}
return 0;
}
| There are 2 problems in your program.
Mistake 1
In Standard C++ the size of an array must be a compile time constant. So take for example,
int n = 10;
int arr[n] ; //INCORRECT because n is not a constant expression
The correct way to write the above would be:
const int n = 10;
int arr[n]; //CORRECT
Mistake 2
You're using an uninitialized variable which leads to undefined behavior. In particular when you wrote:
int n, a[n]; //here variable n is uninitialized and holds **indeterminate value**.
In the above statement, you are creating an int named n but since you have not explicitly initialized it, it holds an indeterminate value.
Next, you're using that garbage value as the size of the array a. But note that using uninitialized variable results in undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
This is why it is advised that
always initialize built in types in local/block scope.
Solution
A better way would be to use std::vector as shown below.
#include <iostream>
#include <vector>
int main()
{
int n = 0; //always initialize built in types in local/block scope
std::cout<<"Enter size: "<<std::endl;
std::cin >> n;
//create a vector of size n
std::vector<int> a(n);
//iterate and ask for input
for(int i = 0; i < a.size(); ++i)
{
std::cout<<"Enter element: "<<std::endl;
std::cin >> a[i];
}
for (int i = 0; i < a.size() - 1; ++i)
{
int index = i;
for (int j = i + 1; j < a.size(); j++) {
if (a[j] < a[index])
index = j;
}
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
std::cout<<"The elements of the vector are:"<<std::endl;
//print the element of the vector
for(const int& elem: a)
{
std::cout<<elem<<std::endl;
}
return 0;
}
The output of the program can be seen here.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
|
70,556,008 | 70,556,098 | Newton-Raphson in Pascal, not very good results | I implemented Newton-Raphson metohd in Pascal. It's strange because the same code in C++ gives good results (for 9 it's 3) but in Pascal for 9 it's 3.25, Why so?
Pascal:
Program NewtonRaphsonIter(output);
{$mode objFPC}
function newton_raphson_iter(a: real; p: real; eps: real; max_i: integer) : real;
var
x: real;
i: integer;
begin
x := a / 2.0;
i := 0;
repeat
x := (x + a / x) / 2.0;
i := i + 1;
if (x * x = a) then break;
if (i >= max_i) then break;
until abs(x - a / x) > eps;
result := x;
end;
var
sqroot: real;
begin
sqroot := newton_raphson_iter(9, 0.001, 0.0000001, 10);
writeln(sqroot);
end.
C++:
#include <iostream>
#include <cmath>
using namespace std;
double sqroot(double num)
{
double x=num/2;
while(fabs(x-num/x)>0.000001)
{
x=(x+num/x)/2;
if(x*x==num) break;
}
return x;
}
int main()
{
cout << sqroot(9.0);
return 0;
}
| repeat ... until C; loop terminates when the expression C evaluates to true. In your code, after the first iteration abs(x - a / x) > eps is true, so the loop terminates.
The termination condition should be inverted:
until abs(x - a / x) <= eps;
Online demo
|
70,556,359 | 70,556,503 | Binary Search with Duplicates | I am doing this particular exercise where I have to implement the Binary Search algorithm which returns the index of the first occurence of an element in a sorted array, if it contains duplicates. Since I am primarily working on my algorithmic skills in C++, I am only trying to do it in C++. Here is my code:
#include <iostream>
#include <cassert>
#include <vector>
using std::vector;
int binary_search(const vector<int> &a, int x, int n) {
int left = 0, right = n-1;
while(left<= right){
int mid = left + (right-left)/2;
if(x== a[mid]){
return mid;
}else if(a[mid]>x){
right = mid-1;
}else{
left = mid+1;
}
}
return -1;
}
int first_occurence(const vector<int>&a, int x, int n) {
int out = binary_search(a, x, n);
if(out !=-1){
for(int i = out;i>0&& a[i]==x;--i ){
out = i;
}
}
return out;
}
int main() {
int n;
std::cin >> n;
vector<int> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
int m;
std::cin >> m;
vector<int> b(m);
for (int i = 0; i < m; ++i) {
std::cin >> b[i];
}
for (int i = 0; i < m; ++i) {
std::cout << first_occurence(a, b[i], n) << ' ';
}
}
The first input to the program tells how many items the array should contain, the second is the enumeration of these elements, third line tells how many keys to search for and the final line are the individual keys. The output is the indices for the key or -1 when no such key is found.
My strategy is to use a function to find the index of a key. If it is found, then in case of duplicates, the first occurrence has to have a lower index. That is what the first_occurence() method does; keep looping back till the first occurence is found.
For the following input:
10
1 5 4 4 7 7 7 3 2 2
5
4 7 2 0 6
The output is:
-1 4 -1 -1 -1
Which is only correct for the key 7. I have been trying to debug this for quite some time but I can not figure out the problem.
|
returns the index of the first occurence of an element in a sorted array,
Your binary search algorithm requires that the data is sorted before you call it.
Example:
#include <algorithm>
#include <sstream>
int main() {
std::istringstream in(R"aw(10
1 5 4 4 7 7 7 3 2 2
5
4 7 2 0 6
)aw");
int n;
in >> n;
vector<int> a(n);
for (auto& v : a) {
in >> v;
}
std::sort(a.begin(), a.end()); // <- add this
// display the sorted result:
for (auto v : a) std::cout << v << ' ';
std::cout << '\n';
int m;
in >> m;
vector<int> b(m);
for (auto& v : b) {
in >> v;
}
for (auto v : b) {
std::cout << v << ' ' << first_occurence(a, v, n) << '\n';
}
}
|
70,556,448 | 70,556,543 | in the c++ hacker rank preperation cause, the last index returns 0 when i reverse it. but when i try the code out in visual studio, it works perfectly | HERE IS THE QUESTION I FACED ON HACKERRANK.
the hackerrank question
HERE IS THE CODE I PRINTED
#include <iostream>
using namespace std;
int main() {
int n;
int array[n];
int c,x;
cin>>n; //inputting the array size
n=n+1;
int m=n;
if(n>=1 && n<=1000 && m>=1 && m<=1000 )
{
for(c=1;c<=n;c++)//inutting the numbers
{ if(c<=10000)
{
cin>>array[c];
}
}
for(x=m-1;x>=1;x--)//outputing the numbers reversed
{
cout<<array[x]<<" ";
}
}
return 0;
}
WHEN I GIVE INPUT THE ARRAY SIZE AS 4 AND THE DATA AS 1 4 3 2,
ITS REVERSED AS 2,3,4,0
BUT IT PERFECTLY GETS REVERSED WHEN COMPILED WITH VISUAL STUDIO CODE. WHYS THAT?? AND ALSO WHEN I SUBMIT CODE SEVERAL TESTS PASS, BUT SOME GET A SEGMENTATION ERROR
| As mentioned in the comments, array should be initialized with a proper capacity. You should first read the size and then create the array.
#include <iostream>
using namespace std;
int main() {
int n;
// First read the array size and then create the array.
cin>>n; //inputting the array size
int array[n];
//inputting the numbers
// Remember indices go from 0 to N-1
for(int c=0;c<n;c++)
{
cin>>array[c];
}
//outputing the numbers reversed
for(int x=n-1;x>=0;x--)
{
cout<<array[x]<<" ";
}
return 0;
}
|
70,556,755 | 70,558,965 | Does implicit object creation apply in constant expressions? | #include <memory>
int main() {
constexpr auto v = [] {
std::allocator<char> a;
auto x = a.allocate(10);
x[2] = 1;
auto r = x[2];
a.deallocate(x, 10);
return r;
}();
return v;
}
Is the program ill-formed? Clang thinks so, GCC and MSVC don't: https://godbolt.org/z/o3bcbxKWz
Removing the constexpr I think the program is not ill-formed and has well-defined behavior:
By [allocator.members]/5 the call a.allocate(10) starts the lifetime of the char[10] array it allocates storage for.
According to [intro.object]/13 starting the lifetime of an array of type char implicitly creates objects in its storage.
Scalar types such as char are implicit lifetime types. ([basic.types.general]/9
[intro.object]/10 then says that objects of type char are created in the storage of the char[10] array (and their lifetime started) if that can give the program defined behavior.
Without beginning the lifetime of the char object at x[2], the program without constexpr would have undefined behavior due to the write to x[2] outside its lifetime, but the char object can be implicitly created due to the arguments above, making the program behavior well-defined to exit with status 1.
With constexpr, I am wondering if the program is ill-formed or not. Does implicit object creation apply in constant expressions?
According to [intro.object]/10 objects are implicitly created to give the program defined behavior, but does being ill-formed count as defined behavior?
If not, then the program should not be ill-formed because of implicit creation of the char object for x[2].
If yes, then the next question would be if it is unspecified whether the program is ill-formed or not, because [intro.object]/10 also says that it is unspecified which objects are implicitly created if multiple sets can give the program defined behavior.
From a language design perspective I would expect that implicit object creation is not supposed to happen in constant expressions, because verifying the (non-)existence of a set of objects making the constant expression valid is probably infeasible for a compiler in general.
|
2469. Implicit object creation vs constant expressions
It is not intended that implicit object creation, as described in 6.7.2 [intro.object] paragraph 10, should occur during constant expression evaluation, but there is currently no wording prohibiting it.
|
70,556,808 | 70,566,628 | while loop running for every digit/character from input | Hey guys beginner in C++ and coding in general. I am currently making a tictactoe program. For the part of the program I am validating user input. Since it is a 3x3 table, I want to make sure their input is an integer and that they choose a number between 1~9.
To do this I wrote
//Validating user input
void move() {
std::cout << "It's Player" << player << "'s turn!\n";
while(!(std::cin >> position)){
std::cout << "Please choose a NUMBER between 1~9!\n";
std::cin.clear();
std::cin.ignore();
}
while(position < 1 || position > 9){
std::cout << "Please choose a number BETWEEN 1~9!\n";
std::cin.clear();
std::cin.ignore();
}
while(board[position - 1] != " ") {
std::cout << "Already filled please choose another number between 1~9!\n";
std::cin >> position;
}
}
It works but for some reason when I put in an input like 10, it would print Please choose a number BETWEEN 1~9! twice (for each digit) and if I input in for example "apple" it would print Please choose a NUMBER between 1~9! four times (for each character). How do i make it just print out the statement once?
Thank you!
| Let me try to explain to you the problem. It is a little bit subtle and not that easy to understand. Both other answers adress only the obvious part.
Then, let us first recap that:
The boolean condition in the while statement is loop invariant. Meaning, it will not be modified within the loop. Whatever it was before the loop, will be the same after the loop body has been executed. The condition will never change.
So, for the case where you enter a wrong number:
If the input number is correct (1..9) and the while statement starts to evaluate the boolean expression, it will be false in this case and the loop will not be entered.
If the number is out of your selected bounds (<1 or >9), then the boolean condition is true. The while loop starts, but the condition relevant variable will not be changed in the loop boody and hence, the boolean expression is always true. The loop will run forever.
Additionally, and now comes the answer to your first question, the following will happen:
The text "Please choose a number BETWEEN 1~9!\n" will be shown (first time)
clear will be called for std::cin. The failbit was not set, but anyway. This does not harm
The ignore function is an unformatted input function. It will actively read the next character from the input buffer, which is the end of line `'\n' character.
We enter again the while statement. The condition is still true (position was not modified in the loop body), and we enter the loop again.
The text "Please choose a number BETWEEN 1~9!\n" will be shown (second time)
clear will be called for std::cin. The failbit was not set, but anyway. This does not harm
The ignore function is a formatted input function. It will actively read the next character from the input buffer. But there is none. So it will wait until a key is pressed. For example "enter". After that, it would go back to number 5.
By the way. If you would now enter "abc" then you would see the text 4 times for a,b,c and enter.
So, please remember: ignore is an input function!
Next. It is important to understand, that if you enter an unexpected value, like "apple" instead of "3", the formatted input function >> can do no conversion and sets the failbit. It will also not extract further wrong characters from the input stream (std::cinis a buffered stream). The characters that could not be converted are still in the buffer and wil be read next time.
Please read here about formatted/unformatted input. And especially read about the extraction operatpr >> here..
There you can read the following:
If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set.
OK, understood. Then, what is going on here, if you enter "abc". Basically, the same as above.
Enter abc
The boolean condition !(std::cin >> position)will be evaluated to true, because an 'a' was read and cannot be converted to a number.
The std::cin's failbit will be set. The variable positionwill be set to 0.
"Please choose a NUMBER between 1~9!\n" will be shown
The failbit will be reset
Ignore will extract exactly the one wrong character and discard it
std::cin >> position`` will be called again and extract the next wrong character 'b'. 3., 4., 5., 6. will be done again. Until the last charcter in the buffer, the newline '\n' will be extracted. Then you may enter the next number.
The fix for that problem is simple:
ignore has a parameter, where you can specify, how many characters shall be ignored. So, not only one, but all until the end of line.
You should write:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
This will ignore all bad input.
And to fix your whole program, you could write at the top:
while (!(std::cin >> position) or (position < 1 ) or ( position > 9)) {
std::cout << "Please choose a NUMBER between 1~9!\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
|
70,557,046 | 70,557,114 | How to use a switch case inside a for loop? | I'm doing a quiz program in C++ programming language. I have used a for loop to go through each switch case but when I run the program, it's just keep looping the case 0 and can't stop the loop after I answering my quiz. How should I solve it ?
#include <iostream>
#include <string>
using namespace std ;
void quiz_count () ;
void display_question () ;
void question (string question , string a , string b , string c , string d , char correct_answer) ;
void result () ;
int question_num = 0 ;
int correct = 0 ;
int wrong = 0 ;
int main ()
{
display_question() ;
return 0 ;
}
void quiz_count ()
{
system("cls") ;
cout << "Question Number: " << question_num << "\t\t Correct Answer:" << correct << "\t\t Wrong Answer:" << wrong << endl << endl ;
display_question () ;
}
void display_question()
{
for (int i=0; i<10 ; i++)
{
switch (i)
{
case 0 :
question ( "1) What is recycling?" , "Buying new clothes" , "Collecting and using materials to make something new" , "Throwing things in garbage can" , "Selling items" , 'b' ) ;
break ;
case 1 :
question ( "2) What are the 3R's of the recycling?" , "Redirect, Rude, Round" , "Respectful, Responsible, Right" , "Reduce, Reuse, Recycle" , "Rewrite, Rewind, Respond" , 'c') ;
break ;
case 2 :
question ( "3) What goes into the green bin?" , "plastic" , "glass" , "cans" , "paper" , 'b' ) ;
break ;
}
}
result () ;
}
void result ()
{
system("cls") ;
cout << "The total of question is :" << question_num << endl ;
cout << "The correct answer from you is :" << correct << endl ;
cout << "The wrong answer from you is :" << wrong << endl ;
}
void question (string question , string a , string b , string c , string d , char correct_answer)
{
cout << question << endl ;
cout << "A. \t" << a << endl ;
cout << "B. \t" << b << endl ;
cout << "C. \t" << c << endl ;
cout << "D. \t" << d << endl ;
char answer ;
cout << "Please enter your answer here :" ;
cin>>answer ;
if (answer == correct_answer)
{
correct ++;
}
else
wrong ++ ;
question_num ++ ;
quiz_count() ;
}
| The issue isn't the loop + switch, but the infinite recursion you're using:
display_question() calls question()
question() calls quiz_count()
quiz_count() calls display_question(), so you're back at step 1.
The values of i you're observing are simply the values for different calls to the display_question function.
You'll probably get the desired outcome by removing the display_question() call from quiz_count. However the combination of loop and switch isn't a good choice here. the following implementation yields the same results in addition to being easier to understand:
void display_question()
{
question ( "1) What is recycling?" , "Buying new clothes" , "Collecting and using materials to make something new" , "Throwing things in garbage can" , "Selling items" , 'b' ) ;
question ( "2) What are the 3R's of the recycling?" , "Redirect, Rude, Round" , "Respectful, Responsible, Right" , "Reduce, Reuse, Recycle" , "Rewrite, Rewind, Respond" , 'c') ;
question ( "3) What goes into the green bin?" , "plastic" , "glass" , "cans" , "paper" , 'b' ) ;
result () ;
}
|
70,557,232 | 70,558,941 | Trying to get a JSON output from cURLlib in c++ | So I'm using cURLlib in C++ so that I can get market data using API's, problem is I'm not able to make head or tails from the documentation given about cURLlib for C++.
The API returns a JSON file which I want to parse and take data from to use on my own algorithm.
The only solution I see right now is to parse the string that's returned by cURL, but I think that seems too lenghty and tacky, so if there's someway I can get a direct output as a JSON file from cURL instead I could use nlohmann and iterate through it that way.
(I have changed the API key provided and replaced it with "demo" in the code)
this is my code so far
#include <iostream>
#include <string>
#include <curl/curl.h>
#include<nlohmann/json.hpp>
using namespace std;
using namespace nlohmann;
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
((string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
void main()
{
string readBuffer;
//we use cURL to obtain the json file as a string
auto curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=1min&apikey=demo");//here demo is the api key
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
vector<string>Entries;
string push;
for (auto it = readBuffer.begin(); it != readBuffer.end(); it++)
{
}
}
So if there's a way for me to get a JSON file as an output it would be amazing
any help would be greatly appreciated
|
The only solution I see right now is to parse the string that's returned by cURL
That is exactly what you need to do.
but I think that seems too lenghty and tacky, so if there's someway I can get a direct output as a JSON file from cURL instead
There is no option for that in libcurl.
I could use nlohmann and iterate through it that way
You already know how to get the JSON from libcurl as a string. The nlohmann parser can parse a JSON string via the json::parse() method, eg:
std::string readBuffer;
// download readBuffer via libcurl...
json j_complete = nlohmann::json::parse(readBuffer);
// use j_complete as needed...
|
70,557,681 | 70,557,779 | Makefile: Compile C++ Files recursively | I am new to makefiles and tried reading resources on the internet to solve my problem, yet I am unable to find a solution.
Basically I am working on a project which contains C++ and Cuda files. Since I like to keep my things structured, I usually use a nested folder structure like this:
|- bin
|- build
| |- cc
| |- cu
|- src
|- makefile
|- main.cpp
My current Makefile looks like this:
CC = g++
NVCC = nvcc
CC_SRC = $(wildcard *.cpp */*.cpp */*/*.cpp */*/*/*.cpp)
CU_SRC = $(wildcard *.cu */*.cu */*/*.cu */*/*/*.cu)
CC_LIBS = -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
ROOT = ./
FOLDER = $(ROOT)bin/
OBJECTS = $(ROOT)build/
CC_OBJ = $(OBJECTS)cc/
CU_OBJ = $(OBJECTS)cu/
NAME = Test
EXE = $(ROOT)$(FOLDER)$(NAME)
NVCC_FLAGS =
CC_FLAGS =
## Compile ##
run:build
build: $(EXE)
$(CC_SRC):
@echo compiling
$(CC) $(CC_FLAGS) -c $< -o $a
$(EXE) : $(CC_SRC)
@echo test 123
Initially I wanted to compile all C++ files to the build/cc files. Similarly my .cu files should be compiled into the build/cu folder.
Initially I made a wildcard which catches all the c++ files:
CC_SRC = $(wildcard *.cpp */*.cpp */*/*.cpp */*/*/*.cpp)
CU_SRC = $(wildcard *.cu */*.cu */*/*.cu */*/*/*.cu)
But for some reason the according rule is not being executed. I am happy if someone could help me here.
Greetings
Finn
| This rule doesn't make sense:
$(CC_SRC):
@echo compiling
$(CC) $(CC_FLAGS) -c $< -o $a
(I assume you mean $@ here not $a). This rule says that the way to create each of the source files is by compiling them. But, make doesn't need to build the source files: they already exist. So it never invokes your rule.
You need your target to be the file you want to create, not the file that already exists. The file you want to create is the object file, not the source file. Then the prerequisite is the file that already exists. So for a compilation you want a pattern rule, like this:
$(CC_OBJ)%.o : %.cpp
@echo compiling
@mkdir -p $(@D)
$(CC) $(CC_FLAGS) -c $< -o $@
Then you want your target to depend on the object files, not the source files, like this:
$(EXE) : $(CC_SRC:%.cpp=$(CC_OBJ)%.o)
@echo test 123
|
70,557,696 | 70,560,263 | decrypting cipher results in missing letters | I have a python endpoint that encrypts string using AES cbc mode and returns it to the client software written in c++ (in a hex space separated format )
The link for the c++ repo
std::vector<unsigned char> cipher_as_chars(std::string cipher)
{
std::istringstream strm{cipher};
strm >> std::hex;
std::vector<unsigned char> res;
res.reserve(cipher.size() / 3 + 1);
int h;
while (strm >> h) {
res.push_back(static_cast<unsigned char>(h));
}
return res;
}
namespace client{
std::string decrypt_cipher(std::string cipher, std::string usr_key)
{
std::string original_text = "";
const std::vector<unsigned char> key = key_from_string(usr_key); // 16-char = 128-bit
const unsigned char iv[16] = {
0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x6e, 0x20, 0x49, 0x56, 0x34, 0x35, 0x36
};
std::vector<unsigned char> encrypted = cipher_as_chars(cipher);
unsigned long padded_size = 0;
std::vector<unsigned char> decrypted(encrypted.size());
plusaes::decrypt_cbc(&encrypted[0], encrypted.size(), &key[0], key.size(), &iv, &decrypted[0], decrypted.size(), &padded_size);
for (int i =0 ; i < decrypted.size(); i++)
{
//cout << decrypted[i] << endl;
std::stringstream stream;
stream << decrypted[i];
original_text = original_text + stream.str();
}
return original_text;
}
}
def encrypt_string(key,text):
result = ''
while len(text)% 16 != 0 :
text = text+" "
string_as_bytes = text.encode('utf8')
obj = AES.new(key.encode("utf8"), AES.MODE_CBC, 'This is an IV456'.encode("utf8"))
cipher_text = obj.encrypt(string_as_bytes)
for item in bytearray(cipher_text):
result += f"{hex(item).replace('0x','')} "
return result
@api.route('/test')
def test_route():
return encrypt_string("Encryptionkey123", "Happy new year people")
The server has an encryption and decryption function same with the client software if I encrypt a string using the c++ code and decrypt it using decryption function written in c++ it works fine and I get the same string, but when the client reads the response of /test and encrypts it and the c++ client tries to decrypt it outputs the string missing n letters in the end
The original text in python server Happy new year people
The output in the c++ client Happy new year p
| Look at this example pycrypto does support pkcs#7 padding your take on padding is poor, just use the built-in padding function in that module
Example taken from the link
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
key=b'1234567890123456'
cipher=AES.new(key,AES.MODE_CBC)
text=b'secret text'
padtext=pad(text,16,style='pkcs7')
cipherText=cipher.encrypt(padtext)
print(padtext)
print(cipherText)
plaintext=cipher.decrypt(cipherText) #can't use same object to decrypt
print(plaintext)
you might want to add some code to turn the result into a hex separated string
|
70,558,153 | 70,558,363 | What happens to uninitialized variables in C/C++? | From "C++ Primer" by Lippman,
When we define a variable, we should give it an initial value unless we are certain that the initial value will be overwritten before the variable is used for any other purpose. If we cannot guarantee that the variable will be reset before being read, we should initialize it.
What happens if an uninitialized variable is used in say an operation? Will it crash/ will the code fail to compile?
I searched the internet for answer to the same but there were differing 'claims'. Hence the following questions,
Will C and C++ standards differ in how they treat an uninitialized variable?
Regarding similar queries, how and where can I find an 'official' answer? Is it practical for an amateur to look up the C and C++ standards?
|
Q.1) What happens if an uninitialized variable is used in say an operation? Will it crash/ will the code fail to compile?
Many compilers try to warn you about code that improperly uses the value of an uninitialized variable. Many compilers have an option that says "treat warnings as errors". So depending on the compiler you're using and the option flags you invoke it with and how obvious it is that a variable is uninitialized, the code might fail to compile, although we can't say that it will fail to compile.
If the code does compile, and you try to run it, it's obviously impossible to predict what will happen. In most cases the variable will start out containing an "indeterminate" value. Whether that indeterminate value will cause your program to work correctly, or work incorrectly, or crash, is anyone's guess. If the variable is an integer and you try to do some math on it, you'll probably just get a weird answer. But if the variable is a pointer and you try to indirect on it, you're quite likely to get a crash.
It's often said that uninitialized local variables start out containing "random garbage", but that can be misleading, as evidenced by the number of people who post questions here pointing out that, in their program where they tried it, the value wasn't random, but was always 0 or was always the same. So I like to say that uninitialized local variables never start out holding what you expect. If you expected them to be random, you'll find that (at least on any given day) they're repeatable and predictable. But if you expect them to be predictable (and, god help you, if you write code that depends on it), then by jingo, you'll find that they're quite random.
Whether use of an uninitialized variable makes your program formally undefined turns out to be a complicated question. But you might as well assume that it does, because it's a case you want to avoid just as assiduously as you avoid any other dangerous, imperfectly-defined behavior.
See this old question and this other old question for more (much more!) information on the fine distinctions between undefined and indeterminate behavior in this case.
Q.2) Will C and C++ standards differ in how they treat an uninitialized variable?
They might differ. As I alluded to above, and at least in C, it turns out that not all uses of uninitialized local variables are formally undefined. (Some are merely "indeterminate".) But the passages quoted from the C++ standards by other answers here make it sound like it's undefined there all the time. Again, for practical purposes, the question probably doesn't matter, because as I said, you'll want to avoid it no matter what.
Q.3) Regarding similar queries, how and where can I find an 'official' answer? Is it practical for an amateur to look up the C and C++ standards?
It is not always easy to obtain copies of the standards (let alone official ones, which often cost money), and the standards can be difficult to read and to properly interpret, but yes, given effort, anyone can obtain, read, and attempt to answer questions using the standards. You might not always make the correct interpretation the first time (and you may therefore need to ask for help), but I wouldn't say that's a reason not to try. (For one thing, anyone can read any document and end up not making the correct interpretation the first time; this phenomenon is not limited to amateur programmers reading complex language standards documents!)
|
70,558,248 | 70,558,336 | Stop computer beeping when printing the number 7 | I'm printing a bunch of ascii chars to the console as a representation of binary numbers however whenever it prints out the number 7 to the console then windows makes a beeping noise.
Looking online I can see some people talking about ascii 7 making a noise but I cant seem to find where to disable it in the code.
for (size_t i = 0; i < 1160; i++)
{
std::cout << "\n" << (char)decimalarray[i];
}
this occurs when the value in the UIN8 array is 7 and I try printing the value as a char.
printing (int)decimalarray[1157] outputs the number 7
printing (char)decimalarray[1157] outputs nothing but makes beeping noise
edit: it would probably be ideal if there was a way to only write printable characters. not easy to hardcode in the values as the program uses every ascii character there is in normal execution.
Can anyone help? thanks
| Code 7 is bell. It is meant to do that.
To disable it, you have 2 choices.
Change the configuration of the terminal or OS (tell it to be silent).
Add a conditional to the code, to skip this character.
To do the conditional: use isprint
e.g.
#include <ctype.h>
#include <iostream>
int main(){
int c =7;
if (isprint(c))
std::cout <<'\n' << static_cast<char>(c);
}
|
70,558,346 | 70,565,649 | Generate random numbers in a given range with AVX2, faster than SVML _mm256_rem_epu32 remainder? | I'm currently trying to implement an XOR_SHIFT Random Number Generator using AVX2, it's actually quite easy and very fast. However I need to be able to specify a range. This usually requires modulo.
This is a major problem for me for 2 reasons:
Adding the _mm256_rem_epu32() / _mm256_rem_epi32() SVML function to my code takes the run time of my loop from around 270ms to 1.8 seconds. Ouch!
SVML is only available on MSVC and Intel Compilers
Are the any significantly faster ways to do modulo using AVX2?
Non Vector Code:
std::srand(std::time(nullptr));
std::mt19937_64 e(std::rand());
uint32_t seed = static_cast<uint32_t>(e());
for (; i != end; ++i)
{
seed ^= (seed << 13u);
seed ^= (seed >> 7u);
seed ^= (seed << 17u);
arr[i] = static_cast<T>(low + (seed % ((up + 1u) - low)));
}//End for
Vectorized:
constexpr uint32_t thirteen = 13u;
constexpr uint32_t seven = 7u;
constexpr uint32_t seventeen = 17u;
const __m256i _one = _mm256_set1_epi32(1);
const __m256i _lower = _mm256_set1_epi32(static_cast<uint32_t>(low));
const __m256i _upper = _mm256_set1_epi32(static_cast<uint32_t>(up));
__m256i _temp = _mm256_setzero_si256();
__m256i _res = _mm256_setzero_si256();
__m256i _seed = _mm256_set_epi32(
static_cast<uint32_t>(e()),
static_cast<uint32_t>(e()),
static_cast<uint32_t>(e()),
static_cast<uint32_t>(e()),
static_cast<uint32_t>(e()),
static_cast<uint32_t>(e()),
static_cast<uint32_t>(e()),
static_cast<uint32_t>(e())
);
for (; (i + 8uz) < end; ++i)
{
//Generate Random Numbers
_temp = _mm256_slli_epi32(_seed, thirteen);
_seed = _mm256_xor_si256(_seed, _temp);
_temp = _mm256_srai_epi32(_seed, seven);
_seed = _mm256_xor_si256(_seed, _temp);
_temp = _mm256_slli_epi32(_seed, seventeen);
_seed = _mm256_xor_si256(_seed, _temp);
//Narrow
_temp = _mm256_add_epi32(_upper, _one);
_temp = _mm256_sub_epi32(_temp, _lower);
_temp = _mm256_rem_epu32(_seed, _temp); //Comment this line out for a massive speed up but incorrect results
_res = _mm256_add_epi32(_lower, _temp);
_mm256_store_si256((__m256i*) &arr[i], _res);
}//End for
| If you range is smaller than ~16.7 million, and you don’t need cryptography-grade quality of the distribution, an easy and relatively fast method of narrowing these random numbers is FP32 math.
Here’s an example, untested.
The function below takes integer vector with random bits, and converts these bits into integer numbers in [ 0 .. range - 1 ] interval.
// Ideally, make sure this function is inlined,
// by applying __forceinline for vc++ or __attribute__((always_inline)) for gcc/clang
inline __m256i narrowRandom( __m256i bits, int range )
{
assert( range > 1 );
// Convert random bits into FP32 number in [ 1 .. 2 ) interval
const __m256i mantissaMask = _mm256_set1_epi32( 0x7FFFFF );
const __m256i mantissa = _mm256_and_si256( bits, mantissaMask );
const __m256 one = _mm256_set1_ps( 1 );
__m256 val = _mm256_or_ps( _mm256_castsi256_ps( mantissa ), one );
// Scale the number from [ 1 .. 2 ) into [ 0 .. range ),
// the formula is ( val * range ) - range
const __m256 rf = _mm256_set1_ps( (float)range );
val = _mm256_fmsub_ps( val, rf, rf );
// Convert to integers
// The instruction below always truncates towards 0 regardless on MXCSR register.
// If you want ranges like [ -10 .. +10 ], use _mm256_add_epi32 afterwards
return _mm256_cvttps_epi32( val );
}
When inlined, it should compile into 4 instructions, vpand, vorps, vfmsub132ps, vcvttps2dq Probably an order of magnitude faster than _mm256_rem_epu32 in your example.
|
70,559,377 | 70,559,567 | Qt or Win32 to obtain notification events for Windows or other systems, users manually switch dark/light mode? | Many articles I read are polling the registry and so on. Is there no corresponding notification event that can be obtained by C/C++?
| In Win32, have a native top-level window (which can be hidden) on your main UI thread listening for WM_SETTINGCHANGE and WM_SYSCOLORCHANGE messages. When you get either event, repoll for screen resolution and desktop color settings.
It's not just light-mode and dark mode you want to monitor for. Also be on the lookout if the user enables a "high contrast" mode.
Here's some sample code you can start with:
struct MyCallback
{
void OnSettingChange()
{
// put your code here
OutputDebugString(L"OnSettingsChange occurred\r\n");
}
void OnColorChange()
{
// put your code here
OutputDebugString(L"OnColorChange occurred\r\n");
}
};
LRESULT __stdcall HiddenWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
MyCallback* pCallback = (MyCallback*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
switch (uMsg)
{
case WM_CREATE:
{
CREATESTRUCT* pCreateData = (CREATESTRUCT*)lParam;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG)(pCreateData->lpCreateParams));
return 0;
}
case WM_PAINT:
{
PAINTSTRUCT ps = {};
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return 0;
}
case WM_SETTINGCHANGE:
{
pCallback->OnSettingChange();
return 0;
}
case WM_SYSCOLORCHANGE:
{
pCallback->OnColorChange();
return 0;
}
default:
{
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
}
return 0;
}
HWND CreateHiddenWindow(HINSTANCE hInstance, MyCallback* pCallback)
{
const wchar_t* CLASSNAME = L"Windows class: 4F98C893-A9E1-4AC4-8E60-68CC220510A7"; // replace with your unique name or guid
WNDCLASSEXW wcex = {};
wcex.cbSize = sizeof(wcex);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = HiddenWindowProc;
wcex.lpszClassName = CLASSNAME;
wcex.hInstance = hInstance;
RegisterClassEx(&wcex);
HWND hWnd = CreateWindow(CLASSNAME, L"Hidden", 0, 0, 0, 0, 0, NULL, NULL, hInstance, pCallback);
return hWnd;
}
|
70,559,589 | 70,559,658 | What is the best way to copy a std::array passed as a parameter? | I've been working on a game written with C++ and SDL2 in my free time and I'm refining some of my base classes for drawable objects. These objects have a position (x and y) and a size (width and height). It makes more sense to me to store these objects in a fixed size array, so I've been using std::array to contain these values in my class since the length is fixed. I'm a little confused on how I should copy the std::array I pass as parameters to the constructor though (and in my setter methods as well)
This is how I have it now
class Drawable {
protected:
std::array<float, 2> position;
std::array<int, 2> drawsize;
SDL_Texture * texture;
public:
// constructor
Drawable(const std::array<float, 2> pos, const std::array<int, 2> size, SDL_Texture* text);
// setters
void set_pos(const std::array<float, 2> &pos) { position = pos; }
void set_size(const std::array<int, 2> &size) { objsize = size; }
};
Drawable::Drawable(const std::array<float, 2> &pos, const std::array<int, 2> &size, SDL_Texture* text) {
position = pos; // like this?
objsize = size; // ???
texture = text;
}
I'm omitting a lot of unnecessary details from the above class to focus on the main issue I'm asking about
I'm confused since I have read that you can copy std::array with assignment (so std::array<int, 5> arr2 = arr1;) but I'm not sure if that is the same when you pass an array as a constant reference as I have (with const std::array<int, 2> &arr). Since I am copying the array anyways, does it even make sense to pass arrays by constant reference? Since they are only of length 2, I have thought about just copying each element into the member variable, but if there is a more readable solution I welcome it.
I'm relatively new to C++ and the containers in the standard library. This is mainly to learn more and have fun :^)
| Either way, by-reference or by-value, is ok.
But don't assign individual elements manually. That is exactly what the assignment/constructor of std::array does for you.
Whether, in general, constructor arguments which will be copied/moved into the class members should be passed by-value or by-reference is a more complicated topic (there are pros and cons to both) which I think should not concern you much if you are new to language.
I would say stick to passing by const reference for now until you learn about move semantics which will give you the context for why by-value passing might be useful. But opinions on this will differ. I am saying it mostly because it is more consistent with advice about passing of other non-scalar types.
If you just pass-by-value (without adding std::move which you probably don't know about yet), then you would make two copies of the object. One for construction of the parameter in the constructor and one to construct/assign the member. Of course, it is likely that the compiler will optimize away one of these away, anyway, assuming the constructor is inlined and the type is simple. (In the case of std::array<float, ...> it doesn't even matter whether std::move is used here.)
There is also an argument to be made that passing small objects by-reference can be worse performance-wise in some situations than passing them by-value, but again, that shouldn't concern you if you are new to the language. This will dependent on the particular situation anyway and it is not obvious when this will be more efficient and when it will be less efficient. In most cases the compiler will probably optimize either variant to the same code anyway (again assuming the constructor can be inlined).
From a performance point of view passing std::array<int,2> and std::array<float,2> specifically by-value is probably the better choice and will probably also be a better choice for slightly larger int or float arrays, but where the cut-off is or whether it actually matters is unclear.
You should however use member initializer lists. What you currently do in your code is to assign the members values. You are not initializing them with the passed objects. To actually initialize them you write:
Drawable::Drawable(const std::array<float, 2> &pos, const std::array<int, 2> &size, SDL_Texture* text)
: position(pos),
objsize(size),
texture(test) {
}
where the members must (theoretically should) be listed in the order in which they are declared in the class.
|
70,559,975 | 70,560,023 | unordered_map elements disappeared after [] operation in c++ | The behavior that unodered_map elements disappeared unexpectedly in the following C++ code confused me a whole lot. In the first for loop I stored the remainder of each element in time moduled by 60 and its count in unordered_map<int, int> m, in the second for loop, I printed the content in m, so far everything seems working right.
cout as following
0:1
39:1
23:1
18:1
44:1
59:1
12:1
38:1
56:2
17:1
37:1
24:1
58:1
However in the third for loop, it only printed part of elements in m,
0:1
39:1
58:1
0:1
it seems many elements in m were erased by n += m[remainder]*m[60-remainder]; operation. I was so confused by this behavior, could you please understand what is going here? Really so confused.
#include <iostream>
#include<unordered_map>
#include<vector>
using namespace std;
int main() {
vector<int> time ({418,204,77,278,239,457,284,263,372,279,476,416,360,18});
int n =0;
unordered_map<int,int> m; // <remiander,cnt>
for (auto t:time)
m[t%60]++;
for (auto [remainder,cnt]:m)
cout<<remainder<<":"<<cnt<<endl;
cout<<endl;
for (auto [remainder,cnt]:m){
cout<<remainder<<":"<<cnt<<endl;
if (remainder==0 || remainder==30)
n += cnt*(cnt-1)/2;
else
n += m[remainder]*m[60-remainder];
}
}
| The third loop uses the [] operator inside the loop.
for (auto [remainder,cnt]:m){
// ...
n += m[remainder]*m[60-remainder];
unordered_map's [] invalidates all existing iterators if it results in a rehash. This includes the implicit iterators employed during range iteration.
As shown, m[remainder] cannot cause a rehash because it can only access an existing value in the unordered map, but this is not true for m[60-remainder], resulting in undefined behavior.
You just need to remove this usage of the [] operator and replace it with the equivalent find() (and, of course, correctly handling the end() value if it gets returned).
|
70,560,112 | 70,560,173 | Array inside Struct wont copy correctly | Was wondering if anyone could help me with this, I have this struct in my code
struct Gate {
int output[9];
};
And i had a vector of that struct, but pushing to the vector which normally would create a copy broke because its only a shallow copy, and my struct has an array
so I tried to work around this by creating a custom copy constructor.
struct Gate {
int output[9];
Gate(const Gate &old){
copy(old.output, old.output + 9, output);
}
};
but now my initializers dont work anymore, because they are trying to use this copy constructor
Gate alwaysFirst{{0,0,0,1,1,1,2,2,2}};
Gate alwaysSecond{{0,1,2,0,1,2,0,1,2}};
universal_gate_finder.cpp:39:41: error: cannot convert '<brace-enclosed initializer list>' to 'const Gate&'
39 | Gate alwaysFirst{{0,0,0,1,1,1,2,2,2}};
|
Does anyone know of a work around for this?
| Gate alwaysFirst{{0,0,0,1,1,1,2,2,2}};
Gate alwaysSecond{{0,1,2,0,1,2,0,1,2}};
These lines use aggregate initialization, which is only possible on aggregates, which cannot have user-declared constructors.
By declaring a custom copy constructor, your type is not aggregate anymore.
You can replace the aggregate initialization with a std::initializer_list constructor or a constructor taking an array by reference, both of which would re-enable that syntax (more or less).
However, it is unnecessary to declare the copy constructor. The implicit copy constructor already constructs the array member from the source object by element-wise copy construction.
Your replacement instead uses copy-assignment which has no benefit over directly copy-constructing the elements.
Declaring a copy constructor also disables the implicit move constructor, which is an additional pessimization.
|
70,560,136 | 70,560,197 | Creating a thread taking way too long | I'm experimenting with threads. My program is supposed to take a vector and sum it by breaking it down into different sections and creating a thread to sum each section. Currently, my vector has 5 * 10^8 elements, which should be easily handled by my pc. However, the creation of each thread (4 threads in my case) takes an insanely long time. I'm wondering why...?
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <algorithm>
#include <numeric>
#include <ctime>
std::mutex m;
int ans = 0;
void sumPart(const std::vector<int>& v, int a, int b){
std::lock_guard<std::mutex> guard(m);
ans += std::accumulate(v.begin()+a, v.begin()+b, 0);
}
void sum(const std::vector<int>& v){
//threadCount is 4 on my pc
int threadCount = std::max(2, (int)std::thread::hardware_concurrency()/2);
int sz = v.size()/threadCount;
std::vector<std::thread> threads;
for(int i = 0; i < threadCount; i++){
clock_t start = clock();
threads.push_back(std::thread(sumPart, v, sz*i, sz*(i+1)));
std::cout << "thread " << i+1 << " took " << (clock()-start)/(CLOCKS_PER_SEC/1000) << " ms to create" << std::endl;
}
for(std::thread& t : threads){
t.join();
}
//the leftovers
ans += std::accumulate(v.begin()+(threadCount)*sz, v.end(), 0);
}
int main(){
const int N = 5e8;
std::vector<int> v(N);
for(int i = 0; i < N; i++){
v[i] = i;
}
sum(v);
std::cout << ans << std::endl;
}
Output:
thread 1 took 681 ms to create
thread 2 took 824 ms to create
thread 3 took 818 ms to create
thread 4 took 814 ms to create
1711656320
Also, if I decrease the number of elements in vector, the time it takes to create each thread decreases as well, which is weird...
(Also I know I'm getting int overflow but that's besides the point)
| std::thread(sumPart, v, sz*i, sz*(i+1))
Arguments to thread functions are copied, as part of creating the execution thread.
Even though sumPart takes it parameter by value v gets internally copied. copying a vector with 500000000 values will take a little bit of time.
You can use std::ref to effectively pass v by reference to your thread function. Note, as it has been mentioned, your lock will single-thread all of your execution threads. However they'll be started very quickly.
|
70,560,461 | 70,560,809 | Sometimes a good practice to initialize a class pointer member variable to itself? | For a strictly internal class that is not intended to be used as part of an API provided to an external client, is there anything inherently evil with initializing a class pointer member variable to itself rather than NULL or nullptr?
Please see the below code for an example.
#include <iostream>
class Foo
{
public:
Foo() :
m_link(this)
{
}
Foo* getLink()
{
return m_link;
}
void setLink(Foo& rhs)
{
m_link = &rhs;
// Do other things too.
// Obviously, the name shouldn't be setLink() if the real code is doing multiple things,
// but this is a code sample.
}
void changeState()
{
// This is a code sample, but play along and assume there are actual states to change.
std::cout << "Changing a state." << std::endl;
}
private:
Foo* m_link;
};
void doSomething(Foo& foo)
{
Foo* link = foo.getLink();
if (link == &foo)
{
std::cout << "A is not linked to anything." << std::endl;
}
else
{
std::cout << "A is linked to something else. Need to change the state on the link." << std::endl;
link->changeState();
}
}
int main(int argc, char** argv)
{
Foo a;
doSomething(a);
std::cout << "-------------------" << std::endl;
// This is a mere code sample.
// In the real code, I'm fetching B from a container.
Foo b;
a.setLink(b);
doSomething(a);
return 0;
}
Output
A is not linked to anything.
-------------------
A is linked to something else. Need to change the state on the link.
Changing a state.
Pros
The benefit to initializing the pointer variable, Foo::link, to itself is to avoid accidental NULL dereferences. Since the pointer can never be NULL, then at worst, the program will produce erroneous output rather than segmentation fault.
Cons
However, the clear downside to this strategy is that it appears to be unconventional. Most programmers are used to checking for NULL, and thus don't expect to check for equality with the object invoking the pointer. As such, this technique would be ill-advised to use in a codebase that is targeted for external consumers, that is, developers expecting to use this codebase as a library.
Final Remarks
Any thoughts from anyone else? Has anyone else said anything substantial on this subject, especially with C++98 in consideration? Note that I compiled this code with a GCC compiler with these flags: -std=c++98 -Wall and did not notice any issues.
P.S. Please feel free to edit this post to improve any terminology I used here.
Edits
This question is asked in the spirit of other good practice questions, such as this question about deleting references.
A more extensive code example has been provided to clear up confusion. To be specific, the sample is now 63 lines which is an increase from the initial 30 lines. Thus, the variable names have been changed and therefore comments referencing Foo:p should apply to Foo:link.
| It's a bad idea to start with, but a horrendous idea as a solution to null dereferences.
You don't hide null dereferences. Ever. Null dereferences are bugs, not errors. When bugs happens, all invariances in your program goes down the toilet and there can be no guarantee for any behaviour. Not allowing a bug to manifest itself immediately doesn't make the program correct in any sense, it only serves to obfuscate and make debugging significantly more difficult.
That aside, a structure pointing into itself is a gnarly can of worms. Consider your copy assignment
Foo& operator=(const Foo& rhs) {
if(this != &rhs)
return *this;
if(rhs->m_link != &rhs)
m_link = this;
else
m_link = rhs->m_link;
}
You now have to check whether you're pointing to yourself every time you copy because its value is possibly tied to its own identity.
As it turns out, there's plenty of cases where such checks are required. How is swap supposed to be implemented?
void swap(Foo& x, Foo& y) noexcept {
Foo* tx, *ty;
if(x.m_link == &x)
tx = &y;
else
tx = x.m_link;
if(y.m_link == &y)
ty = &x;
else
ty = y.m_link;
x.m_link = ty;
y.m_link = tx;
}
Suppose Foo has some sort of pointer/reference semantics, then your equality is now also non-trivial
bool operator==(const Foo& rhs) const {
return m_link == rhs.m_link || (m_link == this && rhs.m_link == &rhs);
}
Don't point into yourself. Just don't.
|
70,560,585 | 70,560,762 | GetAsyncKeyState with held CTRL button and another "toggled" button not working as wanted | I got the following code for testing purposes:
bool test = false;
if (GetAsyncKeyState(VK_LCONTROL) && GetAsyncKeyState(VK_F2) & 1) {
test = !test;
std::cout << test << std::endl;
}
Now what I would like to happen is when I hold down the left control and then press F2 that the instructions are being properly handled.
The problem is that the condition turns to true if I hold LCTRL and then F2 or when I hold F2 and then press LCTRL or when I press LCTRL and then press F2 or when I press F2 and then LCTRL. So no matter which combination of which button to press I use the condition always turns out to be true.
I hope some of you people encountered this at some point and can help with some very much appreciated insight.
| GetAsyncKeyState returns multiple things in its return value. The correct way to check if a key is down is: bool lctrldown = GetAsyncKeyState(VK_LCONTROL) < 0;
That being said, waiting for a user to press F2 implies polling and polling is bad! If you only care about F2 in your own window then you should use TranslateAccelerator in your message loop or handle WM_KEYDOWN.
For a global solution, use RegisterHotKey or a low-level keyboard hook.
In the case of WM_KEYDOWN or a hook, when you get notified about F2 you should then check the state of the control key with GetAsyncKeyState.
|
70,560,629 | 70,560,829 | std::reference_wrapper, constructor implementation explaination | I have been trying to understand the implementation of std::reference_wrapper, from here, which is as follows:
namespace detail {
template <class T> constexpr T& FUN(T& t) noexcept { return t; }
template <class T> void FUN(T&&) = delete;
}
template <class T>
class reference_wrapper {
public:
// types
typedef T type;
// construct/copy/destroy
template <class U, class = decltype(
detail::FUN<T>(std::declval<U>()),
std::enable_if_t<!std::is_same_v<reference_wrapper, std::remove_cvref_t<U>>>()
)>
constexpr reference_wrapper(U&& u) noexcept(noexcept(detail::FUN<T>(std::forward<U>(u))))
: _ptr(std::addressof(detail::FUN<T>(std::forward<U>(u)))) {}
reference_wrapper(const reference_wrapper&) noexcept = default;
// assignment
reference_wrapper& operator=(const reference_wrapper& x) noexcept = default;
// access
constexpr operator T& () const noexcept { return *_ptr; }
constexpr T& get() const noexcept { return *_ptr; }
template< class... ArgTypes >
constexpr std::invoke_result_t<T&, ArgTypes...>
operator() ( ArgTypes&&... args ) const {
return std::invoke(get(), std::forward<ArgTypes>(args)...);
}
private:
T* _ptr;
};
Although the implementation of std::reference_wrapper has been discussed hereand here,but none of it discusses the constructor implementation which i am confused about. My confusions are :
1.) Constructor is a template function , taking a type param (U) different from the template class param T. I have seen member functions of a class being template functions and depending on different type params then the type param of the template class, but i can't think how it is works here. There is a related question here, but i am not able to relate it with my confusion.
2.)I see the second type parameter in the constructor is further used to sfinae out something, but i did not understand howdetail::FUN<T>(std::declval<U>()) is evaluated.
Can someone please explain ?
Edit: This is an example added from microsoft.docs. A snippet of the
example is:
int i = 1;
std::reference_wrapper<int> rwi(i); // A.1
rwi.get() = -1;
std::cout << "i = " << i << std::endl; //Prints -1
With the implementation of reference_wrapper , and from A.1, how is the constructor of the reference_wrapper called ? Assuming that detail::FUN<T>(std::declval<U>() will be called with detail::FUN<T>(std::declval<int>(), should be a substitution failure because of the deleted overload(Assuming std::declval<int> will be read as an rvalue reference to int). What am i missing here ?
| It's a technique you can use when you want the behaviour of the "forwarding reference", U&& in this case, but at the same time restrict what can bind to it.
Deduction of T is aided by the deduction guide provided below. The detail::FUN<T>(std::declval<U>()) is there to ensure that the constructor is disabled when U is deduced to be an rvalue reference, by selecting the deleted overload and producing an invalid expression. It is also disabled if the U is another reference wrapper, in which case the copy constructor should be selected.
Here are a few examples of valid and invalid reference_wrappers:
int i = 1;
// OK: FUN<int>(std::declval<int&>()) is valid
std::reference_wrapper<int> rwi(i);
// error: forming pointer to reference
std::reference_wrapper<int&> rwi2(i);
// OK, uses deduction guide to find T = int
std::reference_wrapper rwi3(i);
std::reference_wrapper rwi4(++i);
// error: cannot deduce T, since there is no deduction guide for
// rvalue reference to T
std::reference_wrapper rwi5(std::move(i));
// error: substitution failure of FUN<int>(int&&)
std::reference_wrapper<int> rwi6(std::move(i));
std::reference_wrapper<int> rwi7(i++);
std::reference_wrapper<int> rwi8(i + i);
std::reference_wrapper<int> rwi9(2);
As you can see, the call to the deleted FUN<T>(T&&) only comes into play in the last 4 cases: when you explicitly specify T, but attempt to construct from an rvalue.
|
70,560,886 | 70,561,145 | Why are my strings not being printed correctly? | I want to write a piece of code to create a list of random potions for D&D 5e from a few given parameter lists. And I was almost done, every bit of code working properly apart from a single line of code.
I expect an output of this sort: "The liquid is: Yellow with flecks of colour.".
Instead, I get this: " with flecks of colour.". Basically, the entire part with:
"The liquid is: " gets omitted. Weirdly enough it works fine in one single case, when the colour is "Dark Red".
Here is the minimal working example:
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <fstream>
#include <sstream>
int main(int argc, char** argv)
{
std::vector<std::string> appearance;
std::vector<std::string> appearance_2;
std::ifstream d_appearance("appearance.txt");//20 entries
std::ifstream d_appearance_2("appearance_2.txt");//20 entries
std::string line;
std::string line_2;
for(int i = 0; i < 20; i++)
{
getline(d_appearance, line);
appearance.push_back(line);
getline(d_appearance_2, line_2);
appearance_2.push_back(line_2);
}
std::random_device generator;
std::uniform_int_distribution<int> twenty_dis(0,19);
std::string p_appearance = appearance[twenty_dis(generator)];
std::string p_appearance_2 = appearance_2[twenty_dis(generator)];
for(int i = 0; i < 1; i++)
{
std::ostringstream s_look;
s_look << "The liquid is; " << p_appearance << " with " << p_appearance_2;
std::string look = s_look.str();
std::cout << look << std::endl;
std::cout << std::endl;
}
return 0;
}
I hope it's ok if I just put the text files here as code blocks:
Appearance
Clear
Blue
Green
Red
Pale Green
Pink
Light Blue
White
Black
Dark Grey
Light grey
Yellow
Orange
Gold
Orange
Bronze
Metallic
Purple
Brown
Dark Red
Appearance_2
flecks of colour.
swirls of colour.
fizzing bubbles.
bubbles suspended in it.
some kind of bone floating in it.
leaves and flowers in it.
two separated liquid phases.
a bright glow.
a soft glow.
stripes of colour.
translucency.
a cloudy murkiness.
blood within it.
dirt floating in it.
chunks of metal in it.
some type of gore from a slain creature.
steam coming from it.
a face in the liquid.
constantly moving and shifting liquid.
a constant heat.
| That could be the problem with line endings. If you created the file in Windows (thus you have "\r\n" line endings) and use this file in Linux, the getline would work differently. It will use '\n' as a delimiter, but will treat '\r' as a separate string. As the result you may get some appearences equal to "\r". At the end of the day you could output that:
std::ostringstream s_look;
s_look << "The liquid is; " << "\r" << " with " << p_appearance_2;
std::string look = s_look.str();
std::cout << look << std::endl;
std::cout << std::endl;
That will override the beginning of the string, so you don't see the "The liquid is; " in the output.
|
70,560,927 | 70,563,402 | Print out bitset quickly in c++ | Im writing a program that outputs binary, and I got alot of it I want to output to the terminal, but this takes along time.
In other places in my program where I want to quickly output strings I use
_putchar_nolock
and for floating point and decimal numbers I use
printf
Currently my code looks like this for outputting binary numbers
for (size_t i = 0; i < arraysize; i++)
{
std::cout << (std::bitset<8>(binarynumbers[i]));
}
the output gives a nice 0s and 1s which is what I want, no hex. Issue is when I ran performance benchmarks and testing, I found that std::cout was significantly slower than _putchar_nolock and printf.
Looking online I could not find a way to use printf on a bitset and have it output 0s and 1s. and _putchar_nolock would seem like it would be just as slow having to do all the data conversion.
Does anyone know a fast and efficient way to output a bitset in c++?
My program is singlethreaded and simple so I dont have an issue putting unsafe code for performance in there, performance is a big issue in the code right now.
Thanks for any help.
| The problem is that cin and cout try to synchronize themselves with the library's stdio buffers. That's why they are generally slow;
you can turn this synchronization off and this will make cout generally much faster.
std::ios_base::sync_with_stdio(false);//use this line
You can also get an std::string from the bitset using the to_string() function. You can then use printf if you want.
|
70,560,964 | 70,561,257 | C++20 concepts using ADL with circular dependency | I'm having a problem with concepts using ADL.
edit 1: I mention ADL since the parse functions are supposed to be overloaded with user defined types.
The from_string_view_parsable concept doesn't see the parse functions below since ADL doesn't apply to them.
The functions would need to be defined or forward declared before the concept's definition, however with the 2nd overload there is a circular dependency so it cannot be done.
https://godbolt.org/z/frn1jKv5E
#include <sstream>
#include <optional>
template <typename T>
concept from_string_view_parsable = requires(std::string_view sv, T& x) {
{ parse(sv, x) };
};
void parse(std::string_view input, int& out)
{
auto ss = std::stringstream{};
ss << input;
ss >> out;
}
template <from_string_view_parsable T>
requires std::default_initializable<T>
void parse(std::string_view input, std::optional<T>& out)
{
out = T{};
parse(input, *out);
}
template <from_string_view_parsable T>
void use_parse(T& t) {
parse("123", t);
}
int main() {
std::optional<int> x;
use_parse(x);
}
Is what I'm trying to do fundamentally wrong or perhaps is there any workaround that would allow me to do it?
| You can defer the requires expression to a type trait, which can be forward-declared:
#include <sstream>
#include <optional>
#include <string_view>
#include <type_traits>
template <typename T>
struct is_from_string_view_parsable;
template <typename T>
concept from_string_view_parsable = is_from_string_view_parsable<T>::value;
void parse(std::string_view input, int& out)
{
auto ss = std::stringstream{};
ss << input;
ss >> out;
}
template <from_string_view_parsable T>
requires std::default_initializable<T>
void parse(std::string_view input, std::optional<T>& out)
{
out = T{};
parse(input, *out);
}
template <from_string_view_parsable T>
void use_parse(T& t) {
parse("123", t);
}
template <typename T>
struct is_from_string_view_parsable : std::bool_constant<
requires(std::string_view sv, T& x) {
{ parse(sv, x) };
}
> {};
int main() {
std::optional<int> x;
use_parse(x);
}
Now, I don't know for sure that this doesn't break any rules, but I don't think it should. Be careful that the evaluation of the constraint does not change at different points in the program.
|
70,561,094 | 70,561,186 | Copying objects when passing by value - how many copies do I end up with? | Let me start off by saying that I'm very new to C++ currently - i have previously only really worked with python and javascript (quite a lot of exposure to python) and so, now that I'm learning C++ to expand my knowledge and understanding of lower level programming concepts I wanted to reach out and ask a specific question here.
Of course, with python I have not needed to worry at all about memory allocation, object copies, passing by value/reference, etc. its a whole new world! (very exciting :D)
The way i learn best is to learn by doing, so i have created a relatively simple blockchain proof of concept.
I wont paste in all my code here, as its a fair amount already, but what I want to check is specifically around how copies of objects are handled.
I am not using any dynamic memory allocation either via new/delete or shared_ptr/make_shared thus far in my code, and if i've understood correctly, all of my objects are being created on the stack - as such once the object goes out of scope, this will be automatically destructed (is this right?).
Let me provide an example here and explain what my specific question is. Consider the following code blocks:
void Blockchain::AddBlock(Block bBlock)
{
if (bBlock.ValidateBlock(_vChain))
{
_vChain.push_back(bBlock);
cout << "Chain Length: " << _vChain.size() << endl;
}
else
{
throw Exceptions::ValidationError();
}
}
void Blockchain::AddTransaction(Transaction &tTransaction)
{
cout << "Adding Transaction to block number " << _vChain.size() + 1 << endl;
bool IsValidated = _ValidateTransaction(tTransaction);
if (!IsValidated)
{
cout << "... not valid" << endl;
}
else
{
// cout << "Valid";
int ChainLength = _vTransaction.size();
if (ChainLength < BlockchainConstants::MAX_BLOCK_SIZE)
{
_vTransaction.push_back(tTransaction);
}
else
{
uint32_t NewIndex = _vChain.size();
Block NextBlock = Block(NewIndex, _vTransaction);
NextBlock.sPrevHash = GetLastBlock().GetHash();
AddBlock(NextBlock);
_vTransaction.clear();
_vTransaction.push_back(tTransaction);
}
}
}
Again, if i've understood correctly, in the above block of code that i've written, once the transaction pool has hit its max capacity (thus triggering the else condition), I am creating a block object based on the transaction pool and the index, this is the first instance. When i call AddBlock() I am passing the object by value, thus creating a copy of the object. Within AddBlock() method i am validating the block, and again pushing the object back into the vector _vChain (again, creating a copy). My question is, at the end of that whole process, am I left with any more than one object? My assumption is that the first object created gets destructed at the end of the else condition in AddTransaction() and the second copy is destructed at the end of AddBlock(), leaving me with just 1 instance of the object in the vector _vChain.
Is my thinking correct here? Apologies for the long question, I just wanted to make sure i had all of the details here for you guys - let me know if there is anything else you need to know to help me out. Would appreciate any help at all!
Cheers
| Your question is a bit unclear since I'm not sure why you'd like to know how many copies are there. Edit your question if you'd like to know more explicit question. I smell XY-problem here.
What you need to know is the variable scope.
I assume _vChain is a class member or global variable somehere so _vChain will have a copy of bBlock if validation is passed in AddBlock(). The input argument will be destructed after leaving the function.
If you want to see the behavior, the most simple way is to place std::cout in both of the constructor and destructor to track the construction and destruction of Block.
Also I suggest to pick a beginning programmer's book in The Definitive C++ Book Guide and List.
|
70,561,150 | 70,561,225 | the function getrandom() only returning -1 | I am attempting to get random numbers out of the getrandom() function however attempting to use it only returns -1 the code i am using below:
#include<iostream>
#include <sys/random.h>
int main(){
void* d = NULL;
ssize_t size = 10;
ssize_t p = getrandom(d, size, GRND_RANDOM);
std::cout << p << std::endl;
}
| getrandom returns the number of bytes written. The first argument is the pointer to a byte buffer (to be filled with random bytes), the second argument is the number of random bytes that you want to be written to the buffer.
Your return value (p) being -1 means that there was an error when writing the random bytes to the buffer. This error in your case is because you are passing in NULL as the pointer to the buffer to be filled.
Try this instead:
#include<iostream>
#include <sys/random.h>
int main(){
unsigned char random_bytes[2]; // buffer where getrandom will store the random bytes
ssize_t size = 2;
ssize_t p = getrandom((void*) &random_bytes[0], size, GRND_RANDOM);
std::cout << "First random value: " << random_bytes[0] << std::endl;
std::cout << "Second random value: " << random_bytes[1] << std::endl;
}
source:
https://man7.org/linux/man-pages/man2/getrandom.2.html
|
70,561,671 | 70,561,733 | Return a python function from Python C-API | I am currently in the process of writing a small python module using the Python API, that will speed up some of the slower python code, that is repeatedly run in a in a simulation of sorts. My issue is that currently this code is takes a bunch of arguments, that in many use cases won't change. For example the function signature will be like: func(x,a,b,c,d,e), but after an initialisation only x will change. I therefore will have the python code littered with lambda x : func(x,a,b,c,d,e) where I wrap these before use. I have observed that this actually introduces quite a bit of calling overhead.
My idea to fix this was to create a PyObject* that is essentially C++ lambda instead of the python one. The main issue with this is that I have not found a way to create PyObjects from C++ lambdas, or even lower level functions. Since functions/lambdas in python can be passed as arguments I assume it is possible, but is there a clean way I'm missing.
| I would seriously consider using swig instead of pybind11 for example. It's just peace of mind. If you don't want to use swig directly, you can at least see what swig does to wrap up features like proxy objects.
http://www.swig.org/Doc2.0/SWIGPlus.html#SWIGPlus_nn38
|
70,562,001 | 70,562,392 | Get return type of current function in C++ | This question is similar to Get return type of function in macro (C++) but it is 10 Years old and is not answered. Any other solution would be accepted.
I want to create an assert macro that only returns from the function if the condition isn't met, Like:
#define ASSERT(X) if(!(X)) return {};
This doesn't work if the containing function returns void, but I don't want to create 2 macros. I want to be able to add/remove return values without changing the code. My idea is to create a helper function:
template<class T>
T re(){
if constexpr( std::is_same<T, void>::value ){
return;
}
else if constexpr( ! std::is_same<T, void>::value ){
return {};
}
}
Now the macro could work like:
double f(int *i){
if(i == nullptr){
typedef std::invoke_result<decltype(&f),int>::type T; // only works for this function
return re<T>();
}
return 1.0;
}
But I require the return type T of the current function without having to call something like ASSERT(i != nullptr, double) because then I could simply use 2 macros. Also, macros like __func__ and std::source_location are only strings.
| This is possible using __PRETTY_FUNCTION__ (GCC, Clang) /__FUNCSIG__ (MSVC), a non-standard extension that gives you the name of the current function, including the return type.
You can analyze the string at compile-time to see if it has void in it or not:
#include <string_view>
struct AnyType
{
template <typename T>
operator T()
{
return {};
}
};
template <bool IsVoid>
auto foo()
{
if constexpr (IsVoid)
return;
else
return AnyType{};
}
#ifndef _MSC_VER
#define FUNCNAME __PRETTY_FUNCTION__
#else
#define FUNCNAME __FUNCSIG__
#endif
#define ASSERT(x) if (!bool(x)) return foo<std::string_view(FUNCNAME).starts_with("void ")>()
void x()
{
ASSERT(0);
}
int y()
{
ASSERT(0);
}
This needs more testing to make sure you can't break it with trailing return types, and by adding various stuff to function definition (attributes, calling conventions, etc).
|
70,562,112 | 70,562,186 | Static Multiplication of Vector Using C++, Program not working | I have got this assignment but this program is not working and output is not getting properly. This program compiles successfully, but it gives error - Segmentation fault (core dumpped). I am not getting why this is happening. Please tell me what is the problem in the below code -
#include<iostream>
using namespace std;
class Vector
{
int *V;
int size;
public:
Vector(int m)
{
V = new int[size=m];
for(int i=0; i< size; i++ )
{
V[i] = 0;
}
}
Vector(const int *a)
{
for(int i=0;i<size;i++)
{
V[i] = a[i];
}
}
int operator * (Vector &y)
{
int sum = 0;
for(int i=0;i<size;i++)
{
sum+= this->V[i] * y.V[i];
}
return sum;
}
void printVector()
{
for(int i=0;i<size;i++)
{
printf("%d\t",this->V[i]);
}
}
};
int main()
{
int x[3] = {1,2,3};
int y[3] = {4,5,6};
Vector V1(3);
Vector V2(3);
V1.printVector();
V2.printVector();
V1 = x;
V2 = y;
V1.printVector();
V2.printVector();
int r = V1*V2;
cout<<endl<<"r = "<<r<<endl;
}
| Vector(const int *a) does not initialize Vector::V, replace it with Vector(const int *a, int size) : Vector(size)
but you will have to replace
V1 = x;
V2 = y;
with
V1 = Vector(x,3);
V2 = Vector(y,3);
This code will result in a memory leak btw.
|
70,563,158 | 70,569,226 | Concept that requires a function to return another concept by value or reference | I'm learning C++ concepts. Now I can write a concept that requires the presence of a function which returns something that satisfies an other concept, but so far only by value (in function getB()).
Function getC() gives an error because: because 'decltype(t.getC())' (aka 'const float &') does not satisfy 'floating_point' and because 'is_floating_point_v<const float &>' evaluated to false. It is a reference after all.
template<typename T>
concept TestConcept =
requires(T t)
{
{t.getA()} -> std::convertible_to<float>;
{t.getB()} -> std::floating_point;
{t.getC()} -> std::floating_point;
};
struct CTest
{
int a = 10.0f;
const float& getA() const {return a;}
const float getB() const {return a;}
//const float getC() const {return a;} // This would be OK
const float& getC() const {return a;} //ERROR
};
What I want from this concept is something like:
void func(const TestConcept auto& test){
std::floating_point c = test.getC();
//...
}
Basically to have a function that returns something that satisfies a concept like std::floating_point by reference or by value. Is it doable? Can something similar to std::is_convertible work there?
| You could define a new concept that accepts floating point references, like so:
template<typename T>
concept FloatingPointReference = std::is_reference_v<T> && std::floating_point<std::remove_reference_t<T>>;
Or if you don't care whether it returns by value or by reference you could check whether the decayed type adheres to the concept.
template<typename T>
concept DecaysToFloatingPoint = std::floating_point<std::decay_t<T>>;
These both accept mutable L value references however, so that is something to think about. You might want to write a concept that only accepts const reference and value for example.
|
70,563,305 | 72,189,396 | Strange unicode error when converting Chinese wide strings to regular strings in C++ | Some of my Chinese software users noticed a strange C++ exception being thrown when my C++ code for Windows tried to list all running processes:
在多字节的目标代码页中,没有此 Unicode 字符可以映射到的字符。
Translated to English this roughly means:
There are no characters to which this Unicode character can be mapped
in the multi-byte target code page.
The code which prints this is:
try
{
list_running_processes();
}
catch (std::runtime_error &exception)
{
LOG_S(ERROR) << exception.what();
return EXIT_FAILURE;
}
The most likely culprit source code is:
std::vector<running_process_t> list_running_processes()
{
std::vector<running_process_t> running_processes;
const auto snapshot_handle = unique_handle(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
if (snapshot_handle.get() == INVALID_HANDLE_VALUE)
{
throw std::runtime_error("CreateToolhelp32Snapshot() failed");
}
PROCESSENTRY32 process_entry{};
process_entry.dwSize = sizeof process_entry;
if (Process32First(snapshot_handle.get(), &process_entry))
{
do
{
const auto process_id = process_entry.th32ProcessID;
const auto executable_file_path = get_file_path(process_id);
// *** HERE ***
const auto process_name = wide_string_to_string(process_entry.szExeFile);
running_processes.emplace_back(executable_file_path, process_name, process_id);
} while (Process32Next(snapshot_handle.get(), &process_entry));
}
return running_processes;
}
Or alternatively:
std::string get_file_path(const DWORD process_id)
{
std::string file_path;
const auto snapshot_handle = unique_handle(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, process_id));
MODULEENTRY32W module_entry32{};
module_entry32.dwSize = sizeof(MODULEENTRY32W);
if (Module32FirstW(snapshot_handle.get(), &module_entry32))
{
do
{
if (module_entry32.th32ProcessID == process_id)
{
return wide_string_to_string(module_entry32.szExePath); // *** HERE ***
}
} while (Module32NextW(snapshot_handle.get(), &module_entry32));
}
return file_path;
}
This is the code for performing a conversion from a std::wstring to a regular std::string:
std::string wide_string_to_string(const std::wstring& wide_string)
{
if (wide_string.empty())
{
return std::string();
}
const auto size_needed = WideCharToMultiByte(CP_UTF8, 0, &wide_string.at(0),
static_cast<int>(wide_string.size()), nullptr, 0, nullptr, nullptr);
std::string str_to(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wide_string.at(0), static_cast<int>(wide_string.size()), &str_to.at(0),
size_needed, nullptr, nullptr);
return str_to;
}
Is there any reason this can fail on Chinese language file paths or Chinese language Windows etc.? The code works fine on regular western Windows machines. Let me know if I'm missing any crucial pieces of information here since I cannot debug or test this on my own right now without access to one of the affected machines.
| I managed to test on a Chinese machine and it turns out that converting a file path from wide string to a regular string will produce a bad file path output if the file path contains e.g. Chinese (non-ASCII) symbols.
I could fix this bug by replacing calls to wide_string_to_string() with std::filesystem::path(wide_string_file_path).string() since the std::filesystem API will handle the conversion correctly for file paths unlike wide_string_to_string().
|
70,563,507 | 70,563,685 | Should I delete pointer from `new` passed to a function which makes into a `shared_ptr`? | In the following code example:
#include <iostream>
class Foo{
};
class Bar{
public:
void addFoo(Foo *foo){
auto my_foo = std::shared_ptr<Foo>(foo);
}
};
int main() {
auto bar = Bar();
bar.addFoo(new Foo());
return 0;
}
Do I need to clean up the pointer created in main() by the bar.addFoo(new Foo) call, or will this be taken care of by Bar which creates a shared_ptr of it? My understanding is that auto my_foo = std::shared_ptr<Foo>(foo); will use the copy constructer to copy this pointer into my_foo leaving the original one dangling, is that correct?
| The very idea of a constructor taking a raw pointer is to pass the ownership to std::shared_ptr. So, no, you don't have to delete a raw pointer passed to std::shared_ptr. Doing this will lead to a double deletions, which is UB.
Note that in general passing a raw pointer is dangerous. Consider the following more generalized example:
void addFoo(Foo *foo){
// some code which could throw an exception
auto my_foo = std::shared_ptr<Foo>(foo);
}
If an exception is throw before my_foo is constructed, foo will leak.
If you have no special reason to pass a raw pointer, consider the following alternative:
class Bar {
public:
template<class... Args>
void addFoo(Args... args){
auto my_foo = std::make_shared<Foo>(args...);
}
};
int main() {
auto bar = Bar();
bar.addFoo();
return 0;
}
Here you pass arguments (if you have any) to construct Foo inside addFoo() instead of constructing Foo before invoking addFoo().
Perfect forwarding of args... could be used if it is needed:
template<class... Args>
void addFoo(Args&&... args){
auto my_foo = std::make_shared<Foo>(std::forward<Args>(args)...);
}
|
70,563,532 | 70,563,970 | Custom slider control in MFC (visual studio) | I am making a slider control in visual studio in MFC, I want to set the range from 14 to 100 and step size should be 0.25 as 14.25, 14.50, 14.75 .
How can can make an custom slider control?
| A CSliderCtrl wraps a trackbar control. As such, the former shares the same limitations with the latter. Specifically, the range is set through the TBM_SETRANGE message (or the TBM_SETRANGEMIN and TBM_SETRANGEMAX messages). Either message takes an integral value, so you cannot have the control operate on fractional values.
If you need the integral values supported by the control to represent fractional values, you will have to perform the mapping in client code (scaling and translation). Possible mappings are:
Set the range from 0 * 4 to (100 - 14) * 4 (i.e. 0 to 344). The control position x represents the value 14 + x / 4.
Set the range from 14 * 4 to 100 * 4 (i.e. 56 to 400). The control position x then represents the value x / 4.
In general, fractional values cannot accurately be represented when using floating point values. In this case, however, there is no loss in accuracy; any integer value divided by a power-of-two (such as 4) can be accurately represented by a floating point value (so long as the result is still in range).
|
70,564,069 | 70,569,134 | constexpr causes a GCC warning when used with string literal | The below code compiles:
#include <iostream>
int main( )
{
const char* const str = "This is a constant string.";
std::cout << str << '\n';
}
However, this one gives a warning:
constexpr char* const str = "This is a constant string.";
Here:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
37 | constexpr char* const str = "This is a constant string.";
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is this a bug in GCC? I'm converting a string to a pointer that is pointing to a constexpr char array. Is this warning valid?
Now making the pointer itself constexpr prevents it from being compiled at all:
const char* constexpr str = "This is a constant string.";
Here:
error: expected unqualified-id before 'constexpr'
37 | const char* constexpr str = "This is a constant string.";
| ^~~~~~~~~
Why can't a pointer be constexpr?
| Whether or not you are using constexpr here is not the issue. You are trying to store a string literal in a char* const which is not a pointer to immutable data (which the string literal is), but rather a pointer with a constant address. A string literal can be stored as const char* or const char* const instead.
const char* str = "This is a constant string."
Adding constexpr would look like this:
constexpr const char* str = "This is a constant string."
|
70,564,215 | 70,565,569 | C++ custom-written strncpy without padding all characters to null is it safe? | #include <iostream>
using namespace std;
struct Packet {
int a;
char b[17];
int c;
};
// char* dest has form char dest[n], src has length <= n and is null-terminated
// After the function, dest should satisfy:
// - If strlen(src)==n, dest is not null terminated
// - If strlen(src) < n, dest[n-1] = dest[strlen(src)] = '\0'
static void strncpy_faster(char* dest, const char* src, size_t n) {
size_t i;
for (i = 0; i < n; i++) {
dest[i] = src[i];
if (src[i] == '\0')
break;
}
//while (i < n) {dest[i] = '\0'; i++;} // C standard strncpy do this
if (i < n)
dest[n - 1] = '\0';
}
string charArrayToString(const char* a, size_t n) {
size_t len = 0;
while (len < n && a[len]!='\0') len++;
return std::string(a, a+len);
}
int main()
{
string s = "12341234123412345";
Packet packet;
strncpy_faster(packet.b, s.c_str(), 17);
cout << charArrayToString(packet.b, sizeof(packet.b)) << "\n";
s = "12345";
strncpy_faster(packet.b, s.c_str(), 17);
cout << charArrayToString(packet.b, sizeof(packet.b));
return 0;
}
I'm dealing with struct that have fixed-size char arrays. Let's say I really, really want to keep struct size small (or I need to send them over network), so std::string is not used in my struct (it cost 32 bytes, while I have multiple small char arrays with size 4-20). I have 2 problems with strncpy:
strncpy 2 char array with same length will emit warning about "potentially not having null-terminated character", which is intended, but I don't need that warning.
strncpy pad ALL leftover characters (from dest[strlen(src) -> n-1]) with '\0'. This is a waste of processing in my program.
So, my strncpy_faster only assign up to 2 positions to '\0': the last element of the array, and the position of strlen(src). Since std::string() requires a null-terminated char array (NTCA), I use charArrayToString() to convert non-NTCA to string.
Is this version of strncpy safe? Are there any C/C++ functions that requires strncpy to fill all leftover bytes with '\0', or do they only need a null terminator? I don't know why the standard requires strncpy to zero-out remaining bytes.
|
Is this version of strncpy safe?
Yes.
It's as safe as strncpy is. So.... not safe.
Are there any C/C++ functions that requires strncpy to fill all leftover bytes with '\0', or do they only need a null terminator?
No function require it.
Notes from Linux man-pages man strcpy:
NOTES
Some programmers consider strncpy() to be inefficient and error
prone. If the programmer knows (i.e., includes code to test!) that
the size of dest is greater than the length of src, then strcpy() can
be used.
One valid (and intended) use of strncpy() is to copy a C string to
a fixed-length buffer while ensuring both that the buffer is not
overflowed and that unused bytes in the destination buffer are zeroed
out (perhaps to prevent information leaks if the buffer is to be
written to media or transmitted to another process via an interprocess
communication technique).
Consider using (and/or implementing) strlcpy. Remember about first rule of optimization.
|
70,564,304 | 70,564,394 | Global variable priority over local variable when global function called in scope of local variable c++ | I just wanted to clarify a gap in my knowledge.
Given the following code:
I would have expected that "Hi" is printed, based purely on the fact that in the scope of foo, the definition of FuncA is overwritten and hence should be called. This does not happen as shown here https://onlinegdb.com/LzPbpFN3R
Could someone please explain what is happening here?
std::function<void()> FuncA;
void FuncB() {
if (FuncA) {
FuncA();
}
}
struct Foo {
void FuncA() {
std::cout << "Hi";
}
void FuncC() {
FuncB();
}
};
int main()
{
Foo foo{};
foo.FuncC();
return 0;
}
| As soon as you call a free function, you are no longer inside the class. And you have lost the special this pointer. A (rather C-ish) way could be:
void FuncB(struct Foo* a) { // expect a pointer to a Foo object
a->FuncA(); // call the method on the passed object
}
struct Foo {
void FuncA() {
std::cout << "Hi";
}
void FuncC() {
FuncB(this); // pass the special this pointer to the function
}
};
|
70,564,799 | 70,564,966 | howt to automate reading input sample test case in c++ | I'm coding Dijkstra algorithm and want to take a lot of test cases and no manual input allowed , I have two main files map.txt and routes.txt , i wanna take numbers as pairs , as shown in photossample test cases
| You can redirect the input to stdin as follows:
freopen("filepath.txt", "permission", stdin);
filepath: It is usually the name of the given input file (usually, in contests, the name is problem-name.txt.
permission: It is usually r or w. r means read which is used with input and w means write which is used with output.
stdin is the standard input, where you could use this to redirect the file to standard input and use the normal cin, and stdout is the standard output which is used to redirect your output to a file.
In your case, you could use
freopen("Map.txt", "r", stdin);
to read your input from a file and then use the normal cin command, and you could use
freopen("Routes.txt", "w", stdout);
to output your results in the needed file.
|
70,565,183 | 70,565,268 | Friend function have no access to struct member declared in class template | Here is the situation:
template <class T>
class A {
struct S {
/* some data */
}
S some_member;
public:
/* some methods */
friend bool B (S);
};
bool B (S s) { //<-- ERROR "S was not declared in this scope"
/* do something */
}
What should I do, to have the program compiled correctly?
| While writing the function B's parameter you have to be
in the scope of the class template A<> and,
also specify "some type" like int(or float etc) as shown below:
bool B (A<int>::S s) { //<-- Added change here
return true;
}
You can use other types as well i have given example for int.
Also, you will need to make S public and add the missing semicolon ; after struct S definition.
|
70,565,699 | 70,566,473 | Is there a SFINAE-template to check if a class has no functions of any kind? | I want to check if a given class has only the following:
Non-static data members
Constructor(s) (default or user-defined)
Destructor (default or user-defined)
This type would be (at least visually declaration-wise) identical to a POD-type apart from the user-defined constructor and destructor. I've tried to find a term for this kind of type but I don't think it exists.
Is there a way to check this, using some SFINAE-hackery?
| No, there's no such method. Consider the following:
struct A { };
struct B { void UniqueFunctionName9814(); };
No SFINAE method can distinguish these, because you can't enumerate member function names, nor can you predict random function names. Hence B::UniqueFunctionName9814 can't be detected, and apart from B::UniqueFunctionName9814 the two classes are identical.
|
70,566,084 | 70,568,173 | How to pass reference type to std::hash | I am creating a Template Cache library in C++-11 where I want to hash the keys. I want to use default std::hash for primitive/pre-defined types like int, std::string, etc. and user-defined hash functions for user-defined types. My code currently looks like this:
template<typename Key, typename Value>
class Cache
{
typedef std::function<size_t(const Key &)> HASHFUNCTION;
private:
std::list< Node<Key, Value>* > m_keys;
std::unordered_map<size_t, typename std::list< Node<Key, Value>* >::iterator> m_cache;
size_t m_Capacity;
HASHFUNCTION t_hash;
size_t getHash(const Key& key) {
if(t_hash == nullptr) {
return std::hash<Key>(key); //Error line
}
else
return t_hash(key);
}
public:
Cache(size_t size) : m_Capacity(size) {
t_hash = nullptr;
}
Cache(size_t size, HASHFUNCTION hash) : m_Capacity(size), t_hash(hash) {} void insert(const Key& key, const Value& value) {
size_t hash = getHash(key);
...
}
bool get(const Key& key, Value& val) {
size_t hash = getHash(key);
...
}
};
My main function looks like this:
int main() {
Cache<int, int> cache(3);
cache.insert(1, 0);
cache.insert(2, 0);
int res;
cache.get(2, &res);
}
On compiling the code above, I get the below error:
error: no matching function for call to ‘std::hash<int>::hash(const int&)’
return std::hash<Key>(key);
Can anyone please help me out here and point out what am I missing or doing it incorrectly?
| In this call you provide the constructor of std::hash<Key> with key:
return std::hash<Key>(key);
You want to use it's member function, size_t operator()(const Key&) const;:
return std::hash<Key>{}(key);
Some notes: Hashing and caching are used to provide fast lookup and having a std::function object for this may slow it down a bit. It comes with some overhead:
typedef std::function<size_t(const Key &)> HASHFUNCTION;
The same goes for the check in getHash() that is done every time you use it:
if(t_hash == nullptr) {
It would probably be better to add a template parameter for what type of hasher that is needed. For types with std::hash specializations, that could be the default. Otherwise size_t(*)(const Key&) could be the default. A user could still override the default and demand that the hash function is a std::function<size_t(const Key &)> if that's really wanted.
If a hash function is to be used, I recommend requiring the user to supply it when a Cache is constructed. That way you can skip the if(t_hash == nullptr) check every time the hash function is used.
First a small type trait to check if std::hash<Key> exists:
#include <functional>
#include <type_traits>
#include <utility>
template <class T>
struct has_std_hash {
static std::false_type test(...); // all types for which the below test fails
template <class U>
static auto test(U u) -> decltype(std::declval<std::hash<U>>()(u),
std::true_type{});
static constexpr bool value = decltype(test(std::declval<T>()))::value;
};
The added template parameter in Cache could then be conditionally defaulted to either std::hash<Key> or size_t(*)(const Key&) and you could disallow constructing a Cache with only a size when a pointer to a hash function is needed:
template <
typename Key, typename Value,
class HASHFUNCTION = typename std::conditional<
has_std_hash<Key>::value, std::hash<Key>, size_t(*)(const Key&)>::type>
class Cache {
public:
// a bool that tells if HASHFUNCTION is a pointer type
static constexpr bool hash_fptr = std::is_pointer<HASHFUNCTION>::value;
Cache(size_t size) : m_Capacity(size) {
static_assert(!hash_fptr, "must supply hash function pointer");
}
Cache(size_t size, HASHFUNCTION hash) : m_Capacity(size), t_hash(hash) {}
private:
// No `if` is needed in getHash() - in fact, this function isn't needed.
// You could just do `t_hash(key)` where you need it.
size_t getHash(const Key& key) const { return t_hash(key); }
HASHFUNCTION t_hash;
};
The usage would be the same as before, except you can't construct a Cache without a hasher:
struct Foo {};
size_t hashit(const Foo&) { return 0; }
int main() {
Cache<int, int> cache(3); // ok, HASHFUNCTION is std::hash<int>
Cache<Foo, int> c2(3, hashit); // ok, HASHFUNCTION is size_t(*)(const Foo&)
// Cache<Foo, int> c3(3); // error: must supply hash function pointer
}
|
70,566,097 | 70,773,835 | How to plot gsl_vector in C++? | Is there a convenient way or a library to plot gsl_vector in C++? For example, if I have two gsl vectors, I would like to plot one on the x-axis and the other on the y-axis for the same figure.
| After some research, I got to know that it is not directly possible to plot gsl_vector in C++. However, I coded a workaround (almost like the one suggested by bitmask) using gnuplot, which solved my problem. Therefore, I am posting an answer to my own question.
Following is my solution:
#include <stdio.h>
#include <gsl/gsl_vector.h>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
void plot(const gsl_vector *x, const gsl_vector *y);
using namespace std;
int main ()
{
int i;
gsl_vector * x = gsl_vector_alloc (10);
gsl_vector * y = gsl_vector_alloc (10);
for (i = 0; i < 10; i++)
{
gsl_vector_set (x, i, i);
gsl_vector_set (y, i, exp(i));
}
plot(x, y);
gsl_vector_free (x);
gsl_vector_free (y);
return 0;
}
void plot(const gsl_vector *x, const gsl_vector *y)
{
string command_filename = "commands.txt";
ofstream command;
string data_filename = "data.txt";
ofstream data;
int j;
string plot_filename = "plot.png";
cout << "\n";
cout << "plot:\n";
cout << " Write command and data files that can be used\n";
cout << " by gnuplot for a plot.\n";
// Create the data file.
data.open ( data_filename.c_str ( ) );
for ( j = 0; j < x->size; j++ )
{
data << " " << gsl_vector_get(x, j)
<< " " << gsl_vector_get(y, j) << "\n";
}
data.close ( );
cout << "\n";
cout << " plot: data stored in '"
<< data_filename << "'\n";
// Create the command file.
command.open ( command_filename.c_str ( ) );
command << "# " << command_filename << "\n";
command << "#\n";
command << "# Usage:\n";
command << "# gnuplot < " << command_filename << "\n";
command << "#\n";
command << "set term png\n";
command << "set output '" << plot_filename << "'\n";
command << "set xlabel 'X'\n";
command << "set ylabel 'Y'\n";
command << "set title 'Plot using gnuplot'\n";
command << "set grid\n";
command << "set style data lines\n";
command << "plot '" << data_filename << "' using 1:2 with lines\n";
command << "quit\n";
command.close ( );
cout << " plot: plot commands stored in '"
<< command_filename << "'\n";
return;
}
In main(), I generated two gsl vectors and then passed them to the plot function. In the plot function, I write these vectors to a file called data.txt. I then generate a command file commands.txt which can then be read by gnuplot using the data.txt file.
After running the code above, I manually write the following command:
gnuplot < commands.txt
in terminal/console to plot the vectors, which yields the following plot:
|
70,566,233 | 70,566,337 | Get projected value from std::ranges algorithms | I am using algorithms from std::ranges (max and max_element) with a projection.
Is it possible for the result to also be the projected value? Currently I have to call the projection function again on the returned value.
Example:
Here I want the size of the longest string, but the algorithms return only the string or an iterator to it.
int main()
{
const std::vector<std::string> vec = {
"foo",
"hello",
"this is a long string",
"bar"
};
//r1 is a string. r2 is an iterator
const auto r1 = std::ranges::max(vec, {}, &std::string::size);
const auto r2 = std::ranges::max_element(vec, {}, &std::string::size);
//I have to call size() again
std::cout << r1 << '\n' << *r2 << '\n';
std::cout << r1.size() << '\n' << r2->size() << std::endl;
}
Compiler Explorer
| You're using an algorithm (max/max_element) on the original range, which can't do anything but give you an element/iterator into the range.
If you want just the projected values, do the projection (via a views::transform) to get the lengths first, and then find the maximum of that
auto const lens = std::views::transform(vec, &std::string::size);
const auto r1 = std::ranges::max(lens);
const auto r2 = std::ranges::max_element(lens);
std::cout << r1 << '\n' << *r2 << '\n'; // prints 21 21
Here's a demo.
As mentioned in this answer, taking the address of std::string::size is not permitted, so you should use a lambda instead. In general though, taking a projection based on a member function works just fine, so long as it's not a std function.
|
70,566,491 | 70,567,232 | How to bump the C++ standard from the CMake command line? | Currently I have a project that needs C++17, therefore in the CMakeLists.txt I have this line pretty early on:
set(CMAKE_CXX_STANDARD 17)
From the command line (cmake) once in a while I want to test that the project also compiles with C++20. (to avoid surprises).
How can I choose to compile with C++20 from command line?
If I do cmake -DCMAKE_CXX_STANDARD=20 then it is later overwritten by the configuration instead of 17 being interpreted as just a minimum requirement.
I could check if the variable is predefined to avoid overwritting but I was looking for a more declative way to specify this.
(I am using cmake around 3.18.)
| The solution is to remove that set command and use target properties instead:
# set(CMAKE_CXX_STANDARD 17)
target_compile_features(myexecutable PUBLIC cxx_std_17)
Then, setting -DCMAKE_CXX_STANDARD=20 on the terminal should work again.
|
70,566,615 | 70,566,692 | c++ string template no matching function for call to basic_string<char> | I am writing common function to convert type T to string:
when T is numeric type just use std::to_string
when others use stringstream operator <<
when T is std::string just return T
template <typename Numeric>
string to_str1(Numeric n){
return std::to_string(n);
}
template <typename NonNumeric>
std::string to_str2(const NonNumeric& v){
std::stringstream ss;
ss << v;
return ss.str();
}
// if T is string just return
std::string to_str2(const std::string& v){
return v;
}
template<typename T>
string to_str(const T& t){
if(std::is_integral<T>::value){
return to_str1(t);
}else{
return to_str2(t);
}
}
test usage:
int a = 1101;
cout << to_str(a) << endl;
string s = "abc";
cout << to_str(s) << endl; // should use to_str2(const std::string& v),but compile error
but compile error:
In instantiation of string to_str1 ..... no matching function for call to to_string(std::__cxx11::basic_string
I don't know why this error, ?
| When you write
if(std::is_integral<T>::value){
return to_str1(t);
}else{
return to_str2(t);
}
Then it is true that the if condition is either always true or always false at runtime, but it is still required that the two branches can be compiled. The first branch however doesn't work with T = std::string.
If you want to exclude branches from being compiled completely (aside from syntax check) based on a compile time constant, then you can use if constexpr:
if constexpr(std::is_integral<T>::value){
return to_str1(t);
}else{
return to_str2(t);
}
This tells the compiler to check the if condition at compile-time and only compile the branch that would be taken.
This requires C++17 or later.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.