question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,792,470 | 69,792,605 | How does this loop work? I am unable to understand it | for(int i=1;i<=n;){
f++;
if((i++==p) || (i++==p))
break;
}
example1 : n=7,p=3,f=0; so the value of f should be 1, right? But it is giving f=2 as output
example2 : n=7,p=4,f=0; it is giving output as f=2
example3 : n=7,p=5,f=0; it is giving output as f=3
Help me understanding this.
| Case 1 When n=7,p=3,f=0 . Lets look at values of different variables while going through the for loop.
Iteration 1
for(int i=1;i<=n;) //here n = 7
{
f++; //here f becomes 1 that is now we have f = 1
if((i++==p) || (i++==p)) // variable i is incremented by 1 and becomes 2 because of the
//first i++. But note the old value of i(which is 1) is returned by i++. So although
//right now i = 2, its old value(which is 1) is compared with the value of variable
//p(which is 3). Since 1 and 3 are not equal the next (i++==p) is evaluated. And so
//again variable i is incremented and becomes 3. But here also the old value of
//i(which is 2) is used to compare with value of variable p(which is still 3). But since
//2 is not equal to 3 the control flow doesn't go inside the `if` and so `break` is not
//executed.
break;
}
Iteration 2
for(int i=1;i<=n;) //here n = 7
{
f++; //here f becomes 2 that is now we have f = 2
if((i++==p) || (i++==p)) // Now i is incremented again because of the first i++ and
//becomes 4. But here also the old value of variable i(which is 3) is used to compare
//with value of variable p(which is 3) and since 3 = 3 the condition is satisfied
//and we go inside the `if` statement and `break` is executed. Note at this point
//the value of f is 2 .That is why you get f =2 as output.
break;
}
Similarly you can work out for Case 2 where n=7,p=4,f=0; .
Note that you can/should use the debugger for this purpose.
|
69,792,537 | 69,792,565 | Limitting the number of numbers using substrings cpp | I'm having trouble limiting the number of letters I wasn't appearing. I'm trying to get just the last two but that has been a difficulty. This is what I did;
if (year.length() > 2) {
year = year.substr(0, 2);
}
For example, if you have the year 2016, just 16 is selected.
| subString first parameter is the starting position and second is the number of strings from that position, so first, we take out the length of the string subtract -2 from it.
the second parameter is 2 because we need two characters.
eg : 2016 , first parameter is year subString(4-2,2);
year.substr(year.length() - 2,2)
|
69,792,804 | 69,793,458 | Why delegated constructor doesn't work as expected UE4 | I am having issues with loading the asset for several weapons in the game, such as AK 47, M11, and so on, the issue here is that I created a c++ class for doing that work which will be
header
UCLASS()
AWeapon_core : public AActor
{
private:
USkeletalMeshComponent* m_skeletal_mesh;
public:
AWeapon_core(FString);
protected:
const FString mk_default_path;
};
cpp
AWeapon_core::AWeapon_core(FString _path)
{
m_skeletal_mesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Weapon_mesh"));
static ConstructorHelpers::FObjectFinder<USkeletalMesh> WEAPON_MESH(*(mk_weapon_mesh_path + _path));
if (WEAPON_MESH.Succeeded())
m_skeletal_mesh->SetSkeletalMesh(WEAPON_MESH.Object);
}
And for the weapons, for example AK-47
header
class AAK47 : public AWeapon_core
{
public:
AAK47();
}
cpp
AAK47::AAK47() : AWeapon_core("The path of the AK47 mesh file")
{
}
Did the same for all of the others weapons but it creates with the same mesh, what could be wrong here?
| Do you realize what you did here?
static ConstructorHelpers::FObjectFinder<USkeletalMesh>
WEAPON_MESH(*(mk_weapon_mesh_path + _path));
It's a STATIC LOCAL variable. It is initialized once. Only once as there is only one instance of AWeapon_core::AWeapon_core() function. All subsequent call to this constructor would use already initialized value.
|
69,793,032 | 69,793,056 | How to pass ostream operator<< as a function in C++? | Is there any way I can pass an std::ostream operator<< as an argument in other function call? For example:
#include <iostream>
template <typename Visitor>
void print(Visitor v, int value)
{
v(value);
}
int main(void)
{
std::cout.operator<<(5); // This works
std::cout << 5; // This works
print(std::cout.operator<<, 5); // Error happens
return 0;
}
The error is:
$ g++ -g main.cpp -o main
main.cpp: In function ‘int main()’:
main.cpp:17:12: error: no matching function for call to ‘print(<unresolved overloaded function type>, int)’
5);
^
main.cpp:4:6: note: candidate: template<class Visitor> void print(Visitor, int)
void print(Visitor v, int value)
^~~~~
main.cpp:4:6: note: template argument deduction/substitution failed:
main.cpp:17:12: note: could not deduce template parameter "Visitor"
I know in C++ we can do operator overloadings like std::ostream& operator<<(std::ostream& out, something); but that's not what I aim to. Let's say I want to work with other printing functions or operators (like std::fout or printf), so I want my print function to be generic as much as possible.
| You can pass a lambda instead.
print([](int value) { std::cout << value; }, 5);
|
69,793,492 | 69,793,649 | My "Roman numerals to integer" code wrong | Can someone tell me why my code is not working and giving the wrong output? I think the logic is correct so I'm not sure which errors I'm making. Thanks
int romanToInt(string s) {
unordered_map<char, int> map ={{'M',1000},{'D',500},{'C',100},{'L',50},{'X',10},{'V',5},{'I',1}};
int result = 0;
for(int i=0;i<s.size();i++)
{
if(map[s[i]]>=map[s[i+1]])
result+=map[s[i]];
else
result+=(map[s[i+1]]-map[s[i]]);
}
return result;
}
Test case
Input: "IV"
Output: 9
Expected: 4
| The thing that's wrong with your code is that you are comparing the ASCII values of characters rather than their numeric values. Also, you should not be adding map[s[i+1]] as you will be adding that value twice (once at step i and at step i + 1). Furthermore, you should be more careful with s[i+1], as the index may be out of bounds. So first, check if the index is n - 1 (the last character).
Here is my approach:
int from_roman(string roman) {
map<char,int> values={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
int i,n=roman.length(),val=0;
for(i=0;i<n;i++)
{
if(i==n-1||values[roman[i]]>=values[roman[i+1]])
val+=values[roman[i]];
else
val-=values[roman[i]];
}
return val;
}
Or a more compact version if you prefer it:
int from_roman(string roman) {
map<char,int> values={{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
int i,n=roman.length(),val=0;
for(i=0;i<n;i++)val+=(i==n-1||values[roman[i]]>=values[roman[i+1]]?1:-1)*values[roman[i]];
return val;
}
|
69,793,746 | 69,793,808 | Why "iscntrl" returns 2? | I want to know why, when I print the instruction iscntrl, the return value is always 2?
I also want to know why the result of the isalpha statement is 1024.
For example:
#include <iostream>
using namespace std;
int main()
{
char lettera = 'c';
char numero = '1';
isalpha(lettera)? cout << lettera << " è un carattere!" : cout << lettera << " non è un carattere!";
isalpha(numero)? cout << numero << " è un carattere!" : cout << numero << " non è un carattere!";
cout << endl << isalpha(lettera) << endl; //print 1024
cout << isalpha(numero) << endl; //print 0
cout << iscntrl(numero) << endl; //print 0
cout << iscntrl(1) << endl; //print 2
}
| The iscntrl() function return value:
A value different from zero (i.e., true) if indeed c is an alphabetic
letter. Zero (i.e., false) otherwise.
The isalpha() function return value:
A value different from zero (i.e., true) if indeed c is a control
character. Zero (i.e., false) otherwise.
So, it returns non-zero value (not 1) when the condition is true. So that's intentional.
Also, a tiny note:
isalpha(lettera)? cout << lettera << " è un carattere!" : cout << lettera << " non è un carattere!";
isalpha(numero)? cout << numero << " è un carattere!" : cout << numero << " non è un carattere!";
Those two statements are very similar, so you should make a function:
inline void printmsg(char ch)
{
std::cout << ch << (isalpha(ch) ? "" : " non") << " è un carattere!";
}
and call it:
printmsg(lettera);
printmsg(numero);
|
69,793,811 | 69,793,872 | How to test if member is integral in concept? | I'm trying to define a concept that tests if a particular member variable (in the example, 'x'), exists and is an integral type. I'm getting stumped though, since v.x returns an int& and thus the std::integral check fails. How can I make this work?
#include <concepts>
template <typename T>
concept isIntegralX = requires(T v) {
{v.x} -> std::integral;
};
template <typename T>
requires isIntegralX<T>
void bar(const T& base)
{
}
class Foo
{
public:
int x{0};
void baz()
{
bar<Foo>(*this);
}
};
int main()
{
return 0;
}
Error:
note: the expression 'is_integral_v<_Tp> [with _Tp = int&]' evaluated to 'false'
| You can change the concept as:
template <typename T>
concept isIntegralX = std::is_integral_v<decltype(T::x)>;
decltype(T::x) yields the exact type int here.
For multiple members you can
template <typename T>
concept isIntegralXandY = std::is_integral_v<decltype(T::x)> && std::is_integral_v<decltype(T::y)>;
|
69,793,888 | 69,794,413 | Unresolved external symbol but the function is defined and implemented | I have a header file, defining the chunk class:
#pragma once
#include <vector>
#include "Tile.h"
#include "Numerics.h"
namespace boch {
class chunk {
public:
chunk();
static const uint defsize_x = 16;
static const uint defsize_y = 16;
std::vector<std::vector<tile*>> tilespace;
tile* getat(vint coords);
void fillc(tile t);
};
}
Then, I defined the implementation of the class in Chunk.cpp file:
#include "Chunk.h"
boch::chunk::chunk() {
tilespace = std::vector<std::vector<tile*>>(defsize_x);
for (int x = 0; x < defsize_x; x++) {
std::vector<tile*> temp = std::vector<tile*>(defsize_y);
tilespace[x] = temp;
}
}
void boch::chunk::fillc(tile t) {
for (int x = 0; x < defsize_x; x++) {
for (int y = 0; y < defsize_y; y++) {
tilespace[x][y] = new tile(t);
}
}
}
boch::tile* boch::chunk::getat(vint coords) {
return tilespace[coords.x][coords.y];
}
(vint is a typedef of boch::vector<int> which is the custom X,Y vector, if that helps)
Then, I use it in the main function in BochGrounds.cpp file:
#include <iostream>
#include "Layer.h"
#include "Gamegrid.h"
int main()
{
boch::layer newlayer = boch::layer(boch::vuint(16, 16));
boch::chunk newchunk = boch::chunk();
boch::gamegrid newgrid = boch::gamegrid();
newchunk.fillc(boch::tile());
newgrid.addchunk(boch::cv_zero, &newchunk);
newgrid.drawtolayer(&newlayer);
newlayer.draw(std::cout);
}
Tile class defines the gamegrid class, chunk includes tile class, gamegrid includes chunk & entity (which includes tile as well). Layer class includes only tile. All header files have #pragma once directive. When trying to compile, I'm getting the following error:
LNK2019 unresolved external symbol "public: __cdecl boch::chunk::chunk(void)" (??0chunk@boch@@QEAA@XZ) referenced in function main
LNK2019 unresolved external symbol "public: void __cdecl boch::chunk::fillc(class boch::tile)" (?fillc@chunk@boch@@QEAAXVtile@2@@Z) referenced in function main
and as the result:
LNK1120 2 unresolved externals
Other StackOverflow answers suggest that the linker cannot see implementations of both fillc() and chunk constructor functions, but I cannot see why if it is even the problem here. Please help. (Linker settings haven't been changed, and are default for MVSC 2019)
| Thanks sugar for the answer. I deleted both header and .cpp files and readded them, and it worked like a charm. I suppose I have added either header or .cpp file just by directly adding a new file to the header/source folder instead of adding it to the project (RMB click on the project > add new item).
|
69,794,336 | 69,794,831 | When initialising member with temporary, how to ensure a single call to temporary's constructor? | Suppose I have a wrapper:
template<typename T>
struct Outer {
T inner;
...
};
, and I want to create an Outer wrapping an Inner, like so:
Outer<Inner> wrapper(Inner(...)); // Inner object is a temporary
Is it possible to declare Outer/Inner such that creating an Outer object from a temporary Inner involves the construction of only a single Inner object? I tried declaring the move constructor for Inner, and having Outer take an rvalue reference to Inner, and even explicitly calling std::move on the temporary, but still, 2 copies of Inner are created:
#include <stdio.h>
#include <utility>
template<typename T>
struct Outer {
T inner;
Outer(T&& inner) : inner(inner) {}
};
struct Inner {
int x;
int y;
Inner(const int x, const int y) : x(x), y(y) { printf("ctor\n"); }
Inner(const Inner& rhs) : x(rhs.x), y(rhs.y) { printf("copy ctor\n"); }
Inner(Inner&& rhs) : x(std::exchange(rhs.x, 0)), y(std::exchange(rhs.y, 0)) {
printf("move ctor\n");
}
Inner& operator=(const Inner& rhs) {
printf("assign\n");
return *this = Inner(rhs);
}
Inner& operator=(Inner&& rhs) {
printf("move assign\n");
std::swap(x, rhs.x);
std::swap(y, rhs.y);
return *this;
}
~Inner() { printf("dtor\n"); }
};
int main() {
Outer<Inner> wrapper(Inner(123, 234));
// SAME: Outer<Inner> wrapper(std::move(Inner(123, 234)));
return 0;
}
Output:
ctor <-- The temporary
copy ctor <-- Yet another instance, from the temporary
dtor
dtor
As shown above, the creation of an Outer instance creates 2 Inners. This seems strange as I thought the temporary can be elided, or at least, invoke the move constructor. Is it possible to instantiate Outer with a single Inner construction?
| I guess you are looking for this:
#include <stdio.h>
#include <utility>
template <typename T> struct Outer {
T inner;
// Outer(T &&inner) : inner(std::move(inner)) {}
template <class... Args> Outer(Args &&...args) :inner(args...) {}
};
struct Inner {
int x;
int y;
Inner(const int x, const int y) : x(x), y(y) { printf("ctor\n"); }
Inner(const Inner &rhs) : x(rhs.x), y(rhs.y) { printf("copy ctor\n"); }
Inner(Inner &&rhs)
: x(std::exchange(rhs.x, 0)), y(std::exchange(rhs.y, 0)) {
printf("move ctor\n");
}
Inner &operator=(const Inner &rhs) {
printf("assign\n");
return *this = Inner(rhs);
}
Inner &operator=(Inner &&rhs) {
printf("move assign\n");
std::swap(x, rhs.x);
std::swap(y, rhs.y);
return *this;
}
~Inner() { printf("dtor\n"); }
};
int main() {
Outer<Inner> wrapper(123, 234);
// SAME: Outer<Inner> wrapper(std::move(Inner(123, 234)));
return 0;
}
|
69,794,538 | 69,794,629 | Function to pick a seemingly random index from an array<string> | I'm having a problem figuring out how to pick a random index from an array<string>.
It's for a card game. Instead of shuffling the deck I wanna use the srand function, inside a function to seemingly pick a random number. But every thing that I try just fails.
Here is part of the array:
array<string, 52> cards = { "Ess \3", "Ess \4", "Ess \5", "Ess \6","2 \3","2 \4" };
The \3 \4 \5 \6 is the symbols of the cards, for example Hearts, Diamond, Spades.
Anyway.. I just wanna pick a seemingly random index of the 52.
When I think I'm getting close I run in to something like this:
"C++ no suitable constructor exists to convert from int to basic_string" something like that.
And I don't get it. I have tried for a very long time. Please help me.
My latest attempt...
string randindex = rand() % 52;
cout << cards[randindex];
This is of course not working for me. Before creating a function i first have to learn how to pick a random index...
| int index = rand() % 52;
string card = cards[index];
Use card variable as you wish.
|
69,794,817 | 69,806,149 | How to share cv::Mat for processing between cpp and python using shared memory | I am using shared memory provided by boost/interprocess/ to share the cv::Mat between model and client (both C++). Now I need to use a model in Python. Can you please tell which is the best way to share the cv::Mat between C++ and Python without changing the present client. Thanks.
| The task was completed using mapped memory to share the cv::Mat between C++ and Python process.
C++ - use boost to copy cv::Mat to a mapped shared memory
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <opencv2/opencv.hpp>
using namespace boost::interprocess;
int main(int argc, char* argv[])
{
imgMat= cv::imread("image.jpg");
windows_shared_memory shmem(open_or_create, "shm", read_write, img_size);
mapped_region region(shmem, read_write);
unsigned char* img_ptr = static_cast<unsigned char*> (region.get_address());
std::memcpy(img_ptr , imgMat.data, img_size);
std::system("pause");
}
Python - read the image from memory using mmap.
import mmap
import cv2 as cv
import numpy as np
if __name__ == '__main__':
shmem = mmap.mmap(-1, image_size ,"shm")
shmem.seek(0)
buf = shmem.read(image_size)
img = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
cv.imwrite("img.png", img)
shmem.close()
|
69,794,825 | 69,795,542 | C++ Project has triggered a breakpoint in Visual Studio 2019 | I am new to using pointers (and Visual Studio too) and I'm trying to make a function which deletes the spaces ' ' from a const array. The function should return another array but without the spaces. Seems pretty simple, the code works in Codeblocks, but in Visual Studio it keeps triggering breakpoints. Any idea what am I doing wrong?
char* removeSpaces(const char* text) {
int length = strlen(text);
char* clone = new char(strlen(text));
strcpy_s(clone,length+1, text);
int i = 0;
do {
if (clone[i] == ' ')
strcpy(clone + i, clone + i + 1);
i++;
} while (i < length);
return clone;
}
What appears after I run the code
| "It works" is the most devious form of undefined behaviour, as it can trick you into believing that something is correct - you're writing outside your allocated memory, and strcpy is undefined when the source and destination overlap.
You used the wrong form of memory allocation:
new char(100): a single char with the value 100
new char[100]: an array of one hundred chars.
(And you need space for the string terminator.)
You also don't need to first copy the input and then laboriously modify the copy by shifting characters, and you don't need strcpy for copying a single character.
Just reserve some space, and then copy only the characters you want to keep from the input.
char* removeSpaces(const char* text)
{
int length = strlen(text);
char* clone = new char[length+1];
int copy_length = 0
for (int original = 0; original < length; original++)
{
if (text[original] != ' ')
{
clone[copy_length] = text[original];
copy_length++;
}
}
clone[copy_length] = 0;
return clone;
}
|
69,794,826 | 69,795,589 | How to provoke crash with c++ futures and reference to local variables? | I would very much like to understand Eric Niebler's warnings about c++ futures and dangling local references (in the section titled "The Trouble With Threads"). I, therefore, wrote a little program, repeated below:
#include <iostream>
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#define BOOST_THREAD_PROVIDES_FUTURE
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
void computeResult(int& i) {
boost::this_thread::sleep_for(boost::chrono::seconds(1));
std::cout << i << std::endl;
i += 1;
}
boost::future<int> doThing() {
int local_state{0};
auto lam = [&]() { return computeResult(local_state); };
auto fut = boost::async(lam);
return fut.then([&](auto&&) { return local_state; }); // OOPS
}
int main() {
auto fun = doThing();
int out = fun.get();
std::cout << out << std::endl;
}
The text states that:
If you’ve programmed with futures before, you’re probably screaming, “Nooooo!” The .then() on the last line queues up some work to run after computeResult() completes. doThing() then returns the resulting future. The trouble is, when doThing() returns, the lifetime of the State object ends, and the continuation is still referencing it. That is now a dangling reference, and will likely cause a crash.
I modified the doThing function a little bit to call computeResult asynchronously but otherwise tried to follow the examples in the text. Unfortunately, the program runs perfectly fine on my computer. Can someone kindly outline how to write a program that crashes reliably, as outlined in Eric Niebler's description?
| Like everyone says, believing that Undefined Behaviour would lead to a crash is misguided.
It's a dangerous believe, because the consequences of UB are much more dire when there is silent data corruption, deadlocks, or indeed nothing easily observable for years (until your program suddenly launches that nuclear missile).
There are tools (like asan/ubsan and valgrind/helgrind) to diagnose many cases before they cause you more pain.
Let's run your sample with GCC or Clang's -fsanitize=address,undefined options you get:
1264
AddressSanitizerAddressSanitizer:DEADLYSIGNAL
:DEADLYSIGNAL
=================================================================
==13854==ERROR: AddressSanitizer: SEGV on unknown address (pc 0x7fc8d475b88e bp 0x613000000040 sp 0x7fc8c4cfe9b0 T1)
==13854==The signal is caused by a READ memory access.
==13854==Hint: this fault was caused by a dereference of a high value address (see register values below). Dissassemble the provided pc to learn which register was used.
/home/sehe/custom/boost_1_77_0/boost/thread/lock_types.hpp:346:14: runtime error: member call on misaligned address 0x6120000004f1 for type 'struct mutex', which requires 8 byte alignment
0x6120000004f1: note: pointer points here
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
^
/home/sehe/custom/boost_1_77_0/boost/thread/pthread/mutex.hpp:61:48: runtime error: member access within misaligned address 0x6120000004f1 for type 'struct mutex', which requires 8 byte alignment
0x6120000004f1: note: pointer points here
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
^
/home/sehe/custom/boost_1_77_0/boost/thread/lock_types.hpp:331:18: runtime error: member call on misaligned address 0x6120000004f1 for type 'struct mutex', which requires 8 byte alignment
0x6120000004f1: note: pointer points here
00 00 00 00 01 00 00 00 00 00 00 00 1e 36 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
^
/home/sehe/custom/boost_1_77_0/boost/thread/pthread/mutex.hpp:70:13: runtime error: member access within misaligned address 0x6120000004f1 for type 'struct mutex', which requires 8 byte alignment
0x6120000004f1: note: pointer points here
00 00 00 00 01 00 00 00 00 00 00 00 1e 36 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
^
1265
(As a sidenote, the given program does cause a crash on my machine/compiler even without the sanitizers)
|
69,795,658 | 69,795,841 | How to implement deep and shallow copy constructors without using a boolean parameter? | I have the following class:
class A {
int small;
std::shared_ptr<B> big;
};
Here, B is a class whose objects are expected to have a very large size.
In my program, I have an original object of class A and then make multiple copies of it, then copies of the copies, etc.
Sometimes, I need to make a deep copy, because all members might be modified. Other times, I know that I won't make any changes to A::big and thus I would like to copy only the pointer in order to save resources (a profiler showed me that this is a bottleneck).
Currently, I have the following:
A(const A& other, bool doDeepCopy):
small{other.small}, big{doDeepCopy ? std::make_shared<B>(*other.big) : other.big} {}
I am aware that using bool parameters is considered bad style, but I don't know what else to do. The default copy constructor makes a shallow copy, and I could encapsulate it within a function A A::makeShallowCopy(). But how should the other constructor look like? The only input it needs is an object of type A, but I obviously cannot have two functions with the same signature.
| Assuming B has a copy constructor, just add:
class A {
int small;
std::shared_ptr<B> big;
public:
A clone() const {
return { small, std::make_shared<B>(*big) };
}
};
So clone() becomes the only way to deep-copy your data.
That's the method used in OpenCV and Eigen for matrices: the copy is shallow by default, and an explicit call to replicate() or clone() is required for deep copies.
|
69,796,012 | 69,796,224 | How to correctly use invoke_result_t? | I am having an issue with type traits that I don't understand, I have created the below minimal example. Why does the second call to foo not compile? It gives the error:
from C:/msys64/mingw64/include/c++/10.3.0/bits/nested_exception.h:40,
from C:/msys64/mingw64/include/c++/10.3.0/exception:148,
from C:/msys64/mingw64/include/c++/10.3.0/ios:39,
from C:/msys64/mingw64/include/c++/10.3.0/ostream:38,
from C:/msys64/mingw64/include/c++/10.3.0/iostream:39,
from invoke_result_test.cpp:1:
C:/msys64/mingw64/include/c++/10.3.0/type_traits: In substitution of 'template<class _Fn, class ... _Args> using invoke_result_t = typename std::invoke_result::type [with _Fn = main()::<lambda(bool&)>; _Args = {bool}]':
invoke_result_test.cpp:6:11: required from here
C:/msys64/mingw64/include/c++/10.3.0/type_traits:2957:11: error: no type named 'type' in 'struct std::invoke_result<main()::<lambda(bool&)>, bool>'
2957 | using invoke_result_t = typename invoke_result<_Fn, _Args...>::type;
Reading around it looks like that the function is not callable so invoke_result has no type to return. I would like to be able to call foo with references so I can return values and non-references but cant work this out. Is this possible? I assume so as STL code manages this. What have I not understood?
Minimal Code:
#include <type_traits>
template <typename F,
typename... A,
typename R = std::invoke_result_t<std::decay_t<F>, std::decay_t<A>...>>
R foo(const F& aF, const A& ...aA)
{
return aF(aA...);
}
int main()
{
bool positive = true;
std::cout << foo([](bool flag) -> int
{
if (flag) return 1;
return -1;
},
positive);
std::cout << foo([](bool& flag) -> int
{
flag = !flag;
if (flag) return 1;
return -1;
},
positive);
}
Thanks.
| The error indicates that the function is not invocable with the given arguments.
std::invoke_result automatically adds && to argument types, unless they already have &. Your function is not invocable with a bool && argument.
Even ignoring invoke_result, this couldn't work because foo receives parameters by const references.
You need perfect forwarding for such wrappers:
template <typename F, typename... A>
decltype(auto) foo(F &&f, A &&... a)
{
return std::forward<F>(f)(std::forward<A>(a)...);
}
Here, the return type can be manually specified as std::invoke_result_t<F, A...>.
But then for consistency you should also replace the manual f call with std::invoke (to support calling things like pointers-to-members).
template <typename F, typename... A>
std::invoke_result_t<F, A...> foo(F &&f, A &&... a)
{
return std::invoke(std::forward<F>(f), std::forward<A>(a)...);
}
|
69,796,302 | 69,797,364 | C++ constructor or recursive member function when using templates | I am writing a matrix library, and when I tested the determinant of the matrix, I found this error
I rarely use templates and can’t find the reason for the error
template<int n>
struct Vec{
double data[n]{0};
Vec() = default;
explicit Vec(int value) { ... }
};
template<int row, int col>
struct Mat{
Vec<col> data[row];
explicit Mat() { ... }
Mat(std::initializer_list<double> list) { ... }
Mat<row - 1, col - 1> Minor(const int x, const int y) const{
Mat<row - 1, col - 1> ret;
...
return ret;
}
double Cofactor(const int x, const int y) const{
return Minor(x, y).Det() * ((x + y) % 2 ? -1 : 1);
}
double Det() const{
assert(row == col);
if(row == 1 && col == 1) return data[0][0];
double ret = 0;
for(int i = 0; i < col; ++i){
ret += data[0][i] * Cofactor(0, i);
}
return ret;
}
};
Unable to call Det
Mat<3, 3> matrix{2, 6, 3,
1, 0, 2,
5, 8, 4};
std::cout << matrix.Det() << std::endl;
The error message is as follows
| If your compiler supports at least C++17, then the solution is using if constexpr:
double Det() const{
static_assert(row == col);
if constexpr(row == 1 && col == 1) return data[0][0];
else
{
double ret = 0;
for(int i = 0; i < col; ++i){
ret += data[0][i] * Cofactor(0, I);
}
return ret;
}
}
This is C++ aspect of it. From an algorithmic perspective, computing determinants by definition (i.e. using the Kronecker method), as you do, leads to exponential complexity as a function of matrix size. Algorithms exist that are only a cube of matrix size.
|
69,796,979 | 69,797,018 | what is the meaning of this line of code? | Here is the code.
std::shared_ptr<MyType> f() const { return f_; }
I understand that std::share_ptr is a smart pointer. MyType is a template parameter. f() is a function, right? const here means this function will be read-only. And then what is the relation between the function definition/body and this smart pointer? Many thanks for your comments.
EDIT: I just realized that std::shared_ptr<MyType> is the function return type from all your comments/answers. Now, my question is, f_ is an object of std::shared_ptr<MyType>, is it correct? How do I know that? Do I need to declare the variable f_ anywhere? This is a piece of code from my working_on project and I did not find it very clear about the variable f_ or is there anything else I need to know about the relation between method f and variable f_?
| The above code snippet can be read as:
f is a const member function that returns a std::shared_ptr<MyType> that is it returns a shared_ptr<> to MyType object.
As you already mentioned that the function is read-only, is there something else you want to ask, if there is you can edit your question. Also,note that the variable f_ that you're returning from inside the body of function f is of type std::shared_ptr<MyType> .
Answer to your Edit
Do I need to declare the variable f_ anywhere?
The below example shows one possible scenario:
#include <iostream>
#include <memory>
class MyType
{
int value = 0;
//some other things here
public:
MyType()
{
std::cout<<"MyType Default constructor"<<std::endl;
}
};
class Name
{
std::shared_ptr<MyType> f_ = std::make_shared<MyType>(); //note that you can also write std::shared_ptr<MyType> f_{new MyType};
public:
std::shared_ptr<MyType> f() const //f is a const member function returning std::shared_ptr<MyType>
{
std::cout<<"inside const member function f"<<std::endl;
return f_;
}
};
int main()
{
const Name n;
n.f();
return 0;
}
The output of the program can be seen here.
|
69,797,538 | 69,797,641 | How do I destruct a dynamically allocated array of dynamic object? | I write a class vector whose member is a dynamically allocated array
template <typename T> struct vector{
T* elem;int capacity;
/*
*capacity is the size of array, not number of elements in the array .
*the default capacity is 3.
*/
vector(int c=3,T e=0){ /* initializing all elements as e */
T* elem=new T[capacity = c];
for(int i=0;i<capacity;i++){
elem[i]=e;
}
}
~vector(){
delete[] elem;
}
};
Now this is the point, regarding the destructor of vector. If the elements in the member elem is also dynamically allocated object obj, and this object also has its own destructor
int main(){
vector<obj*> vec;
vec.elem[0] = new obj(parameter)
vec.elem[1] = new obj(parameter)
vec.elem[2] = new obj(parameter)
...
}
Is it necessary to delete all the objects in the destructor of vector? like this
~vector(){
for(int i=0;i<capacity;i++){
delete elem[i];
}
delete[] elem;
}
Or I should only delete[] elem and the destructor of obj will finish the rest of work?
|
Is it necessary to delete all the objects in the destructor of vector? like this
Technically yes but what if you want a vector of pointers that does not represent ownership? You could easily end up either double-deleting an object, or trying to delete a stack-based object:
obj obj_a;
obj* obj_b = new obj;
vector<obj*> obj_ptrs;
obj_ptrs.elem[0] = &obj_a;
obj_ptrs.elem[1] = &obj_a;
obj_ptrs.elem[2] = obj_b;
delete obj_b;
Whether the pointed objects need to be deleted with the vector is none of the vector's business.
The cleanest way to address that is to use std::unique_ptr, which is an object type that holds a pointer and deletes it when it gets destroyed:
#include <memory>
template <typename T> struct vector {
// ...
~vector() {
// The vector is only responsible for deleting the array.
delete[] elem;
}
};
// ...
void foo() {
vector<std::unique_ptr<obj>> obj_ptrs;
obj_ptrs.elem[0] = std::make_unique<obj>();
obj_ptrs.elem[1] = std::make_unique<obj>();
obj_ptrs.elem[2] = std::make_unique<obj>();
obj stack_obj;
vector<obj*> obj_no_own_ptrs;
obj_no_own_ptrs.elem[0] = obj_ptrs.elem[0].get();
obj_no_own_ptrs.elem[1] = obj_ptrs.elem[0].get();
obj_no_own_ptrs.elem[2] = &stack_obj;
// Everything gets deleted
// No double-delete concern
}
|
69,798,309 | 69,798,587 | Applying memoization makes golom sequence slower | I am trying to wrap my head around memoization using c++, and I am trying to do an example with the "golom sequence"
int main(int argc, char* argv[])
{
std::unordered_map<int, int> hashTable;
int value = 7;
auto start = std::chrono::high_resolution_clock::now();
std::cout << golomS(4, hashTable) << std::endl;
auto stop = std::chrono::high_resolution_clock::now();
auto start1 = std::chrono::high_resolution_clock::now();
std::cout << golom(4) << std::endl;;
auto stop1 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
auto duration1 = std::chrono::duration_cast<std::chrono::microseconds>(stop1 - start1);
std::cout << "Time taken by function 1: "
<< duration.count() << " microseconds" << std::endl;
std::cout << "Time taken by function 2: "
<< duration1.count() << " microseconds" << std::endl;
return 0;
}
int golom(int n)
{
if (n == 1) {return 1;}
return 1 + golom(n - golom(golom(n - 1)));
}
int golomS(int n, std::unordered_map<int, int> golomb)
{
if(n == 1)
{
return 1;
}
if(!golomb[n])
{
golomb[n] = 1 + golomS(n - golomS(golomS(n - 1, golomb), golomb), golomb);
}
return golomb[n];
}
As an output I get this:
4
4
Time taken by function 1: 687 microseconds //This is Golom S
Time taken by function 2: 242 microseconds //This is Golom
Shouldn't GolomS be faster with memoization? I tried wrapping my head around the debugger, but im not sure where the effective "slowness" is coming from.
My question is: How can I change the method I made golomS, to be faster than golom.
Thank you. -Adam
| On top of the other answers, I would like to add that this could really benefit from proper benchmarking.
In order to get reliable results you want to run the tests multiple times, and take steps to ensure that memory caches and other system-level shenanigans aren't interfering with the results.
Thankfully, there are libraries out there that can handle most of these complexities for us. For example, here's a better benchmark of your code using google's Benchmark library:
N.B. the fixes proposed by the other answers have been integrated.
#include <chrono>
int golom(int n)
{
if (n == 1) {return 1;}
return 1 + golom(n - golom(golom(n - 1)));
}
int golomS(int n, std::unordered_map<int, int>& golomb)
{
if(n == 1)
{
return 1;
}
if(!golomb[n])
{
golomb[n] = 1 + golomS(n - golomS(golomS(n - 1, golomb), golomb), golomb);
}
return golomb[n];
}
static void TestGolomb(benchmark::State& state) {
for (auto _ : state) {
benchmark::DoNotOptimize(golom(state.range(0)));
}
}
BENCHMARK(TestGolomb)->DenseRange(1, 17, 2);
static void TestGolombS(benchmark::State& state) {
for (auto _ : state) {
// Make sure we always start from a fresh map
std::unordered_map<int, int> golomb;
// Ignore construction and destruction of the map
auto start = std::chrono::high_resolution_clock::now();
benchmark::DoNotOptimize(golomS(state.range(0), golomb));
auto end = std::chrono::high_resolution_clock::now();
auto elapsed_seconds =
std::chrono::duration_cast<std::chrono::duration<double>>(
end - start);
state.SetIterationTime(elapsed_seconds.count());
}
}
BENCHMARK(TestGolombS)->DenseRange(1, 17, 2);
Which gives us the following profile suggesting that the breakeven point is around 14-15:
see on quick-bench
|
69,798,894 | 69,799,319 | K-Nearest Neighbors program always reports same class value | I've written a short implementation of the KNN algorithm to determine a sample point {5.2,3.1}'s class according to a brief snippet of the iris dataset, however the class is always reported as 1 (Virginica). It is not immediately obvious to me where the issue arises in my code. Can someone please help me figure out where/why this occurs?
#include <iostream>
#include <math.h>
#include <string>
//Setosa = 0, Virginica = 1, Verscicolor = 2
//[0] and [1] = data point, [2] = class, [3] = distance
double train_data[15][3] = {
{5.3,3.7,0},{5.1,3.8,0},{7.2,3.0,1},
{5.4,3.4,0},{5.1,3.3,0},{5.4,3.9,0},
{7.4,2.8,1},{6.1,2.8,2},{7.3,2.9,1},
{6.0,2.7,2},{5.8,2.8,1},{6.3,2.3,2},
{5.1,2.5,2},{6.3,2.5,2},{5.5,2.4,2}
};
double Distance(double attr1, double attr2, double sAttr1, double sAttr2)
{
return sqrt(pow(attr1-sAttr1, 2.0)+pow(attr2-sAttr2, 2.0));
}
int findMaxIndex(float *classes)
{
int maxIndex = 0;
for (int i = 0; i < 3; i++){
if (classes[i] > classes[maxIndex])
maxIndex = i;
}
return 0;
}
int main(){
for(int i = 0; i < 15; i++){
train_data[i][3] = Distance(train_data[i][0],train_data[i][1],5.2,3.1);
}
for(int i = 0; i < 15; i++){
for (int j = i+1; j < 15; j++){
if (train_data[i][3] < train_data[j][3]){
//swap
for(int k = 0; k < 4; k++){
double temp = train_data[i][k];
train_data[i][k] = train_data[j][k];
train_data[j][k] = temp;
}
}
}
}
//Based on a value for k determine the class
int K = 5;
float *classes = new float[3];
for (int i =0; i < 3; i++){
classes[i] = 0;
}
for (int i = 0 ; i < K; i++)
{
classes[(int)train_data[i][2]-1]++;
}
int predictedLabel = findMaxIndex(classes)+1;
std::cout << "Predicted class for point {5.2,3.1} is: " << predictedLabel << std::endl;
return 0;
}
| If you enable warnings, you'll see that
test.cpp|33 col 32| warning: array subscript 3 is above array bounds of ‘double [3]’ [-Warray-bounds]
|| 33 | train_data[i][3] = Distance(train_data[i][0],train_data[i][1],5.2,3.1);
Array indexes start at 0.
Later on, you also subtract (class - 1) to index the classes array. Oops. That was already zero-based, so it will become negative.
Consider avoiding the whole source of errors:
struct {
double x, y;
int _class = 0;
double distance = 0;
} train_data[] = {
{5.3, 3.7, 0}, {5.1, 3.8, 0}, {7.2, 3.0, 1}, //
{5.4, 3.4, 0}, {5.1, 3.3, 0}, {5.4, 3.9, 0}, //
{7.4, 2.8, 1}, {6.1, 2.8, 2}, {7.3, 2.9, 1}, //
{6.0, 2.7, 2}, {5.8, 2.8, 1}, {6.3, 2.3, 2}, //
{5.1, 2.5, 2}, {6.3, 2.5, 2}, {5.5, 2.4, 2} //
};
for(auto& node : train_data) {
node.distance = Distance(node.x, node.y, 5.2, 3.1);
}
Also note that std::swap(node1, node2) will just work. Or make the node type sortable.
More Idiomatic C++
Here's my take
Live On Coliru
#include <array>
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
//Setosa = 0, Virginica = 1, Verscicolor = 2
enum Class { Setosa, Virginica, Verscicolor, NCLASSES };
struct node {
double x, y;
Class _class = Setosa;
double distance = 0;
bool operator<(node const& other) const {
return distance > other.distance;
}
};
std::vector<node> train_data{
{5.3, 3.7, Setosa}, {5.1, 3.8, Setosa}, {7.2, 3.0, Virginica}, //
{5.4, 3.4, Setosa}, {5.1, 3.3, Setosa}, {5.4, 3.9, Setosa}, //
{7.4, 2.8, Virginica}, {6.1, 2.8, Verscicolor}, {7.3, 2.9, Virginica}, //
{6.0, 2.7, Verscicolor}, {5.8, 2.8, Virginica}, {6.3, 2.3, Verscicolor}, //
{5.1, 2.5, Verscicolor}, {6.3, 2.5, Verscicolor}, {5.5, 2.4, Verscicolor} //
};
double Distance(double x1, double y1, double x2, double y2) {
return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
}
// Based on a value for k determine the class
Class predict(double x, double y, unsigned K) {
for (auto& node : train_data) {
node.distance = Distance(node.x, node.y, x, y);
}
sort(train_data.begin(), train_data.end());
// tally buckets:
std::array<unsigned, NCLASSES> classes = {0, 0, 0};
for (unsigned i = 0; i < K; i++) {
classes[train_data[i]._class]++;
}
auto index = std::max_element(classes.begin(), classes.end()) //
- classes.begin();
return static_cast<Class>(index);
}
int main()
{
std::cout << "Predicted class for point {5.2,3.1} is: "
<< predict(5.2, 3.1, 5) << "\n";
}
Prints
Predicted class for point {5.2,3.1} is: 1
I do suspect you had the sorting order inverted? With the sort order flipped:
Live On Coliru
Predicted class for point {5.2,3.1} is: 0
|
69,800,105 | 69,804,564 | c++ combine multiple std::find & std::find reverse starting in the middle of the vector | Im having trouble to find some elements the most speedy way.
Given the two vectors I want to start searching elements starting at a previously given position (3), and compare them to another vector. Because i know the "valid" values are 99% around the starting point im trying to build a mechanism, that has 4 steps:
Valid positions are: vec1[i] == 1 && vec2[i] != vec1[5]
vec1 : 1, 0, 0, 1, 0, (3), 0, 0, 0, 0, 0, 1, 0, 1
vec2 : 3, 0, 0, 3, 0, (0), 0, 0, 0, 0, 0, 3, 0, 0
1: ^======S fail: vec1[5] == vec2[3]
2: S==================^ fail: vec1[5] == vec2[11]
3: ^========S fail: vec1[5] == vec2[0]
4: S=====^ good: vec1[5] != vec2[13]
I tried to implement this with this code:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> vec1 = {1, 0, 0, 1, 0, 3, 0, 0, 0, 0, 0, 1, 0, 1};
std::vector<int> vec2 = {1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0};
auto down1 = std::find(vec1.rbegin() + 5, vec1.rend(), 1);
//first search down for first element
if (down1 != vec1.rend() && vec2[5] != vec1[std::distance(down1, vec1.rend()) - 1])
{
std::cout << "First downsearch: '1' found and Vec2[" << std::distance(down1, vec1.rend()) - 1 << "] is not the same as Vec1[5]" << std::endl;
// in loop I do continue; here
}
auto up1 = std::find(vec1.begin() + 5, vec1.end(), 1);
if (up1 != vec1.end() && vec2[5] != up1 - vec1.begin())
{
std::cout << "First upsearch: '1' found and Vec2[" << up1 - vec1.begin() << "] is not the same as Vec1[5]" << std::endl;
// in loop I do continue; here
}
//second search down, starting at down1 <<<--- not working
auto down2 = std::find(down1, vec1.rend(), 1);
if (down2 != vec1.rend() && vec2[5] != vec1[std::distance(down2, vec1.rend()) - 1])
{
std::cout << "Second downsearch: First '1' found and Vec2[" << std::distance(down2, vec1.rend()) - 1 << "] is not the same as Vec1[5]" << std::endl;
// in loop I do continue; here
}
return 1;
}
But I think i fail with using the first down iterator for the second down search..
Note: The Element I’m trying to find for can occur at maximum two times. One time it fits the condition, one time it does not.
Do you have any ideas? Thank you!! :-)
Right now I’m using just a while loop to incrementely search one below, then one up, two below, two up.. I assumed std::find would be a better solution, because sometimes the values are very far away. (1%)
| First, your code is a bit confusing because in the condition you compare to vec2[5] but in the message you say Vec1[5].
Second, I'm not really sure why do you use std::distance instead of just de-referencing the iterator:
if (down1 != vec1.rend() && vec2[5] != *down1)
And finally, your last std::find doesn't work as you expected because you start at down1, which already points to the searched value. You want to start searching from the next element:
auto down2 = std::find(down1+1, vec1.rend(), 1);
But be careful, down1 may be rend at this point so you should check for that first.
|
69,800,678 | 69,800,865 | Complexity of a function with 1 loop | Can anyone tell me what's the complexity of the below function? And how to calculate the complexity?
I am suspecting that it's O(log(n)) or O(sqrt(N)).
My reasoning was based on taking examples of n=4, n=8, n=16 and I found that the loop will take log(n) but I don't think it'll be enough since sqrt also will give the same values so I need to work on bigger values of n, so I am not sure how to approach this.
I had this function in the exam today.
void f(int n){
int i=1;
int j=1;
while(j <= n){
i += 1;
j += i;
}
}
| The sequence j goes through is 1 3 6 10 15 21, aka the triangular numbers, aka n*(n+1)/2.
Expanded, this is ( n^2 + n ) / 2. We can ignore the scaling ( / 2) and linear ( + n) factors, which leaves us with n^2.
j grows as a n^2 polynomial, so the loop will stop after the inverse of that growth:
The time complexity is O(sqrt(n))
|
69,801,126 | 69,801,186 | Doesn't constraining the "auto" in C++ defeat the purpose of it? | In C++20, we are now able to constrain the auto keyword to only be of a specific type. So if I had some code that looked like the following without any constraints:
auto something(){
return 1;
}
int main(){
const auto x = something();
return x;
}
The variable x here is deduced to be an int. However, with the introduction of C++20, we can now constrain the auto to be a certain type like this:
std::integral auto something(){
return 0;
}
int main(){
const auto x = something();
return x;
}
Doesn't this defeat the purpose of auto here? If I really need a std::integral datatype, couldn't I just omit the auto completely? Am I misunderstanding the use of auto completely?
| A constraint on the deduced auto type doesn't mean it needs to be a specific type, it means it needs to be one of a set of types that satisfy the constraint. Note that a constraint and a type are not the same thing, and they're not interchangeable.
e.g. a concept like std::integral constrains the deduced type to be an integral type, such as int or long, but not float, or std::string.
If I really need a std::integral datatype, couldn't I just omit the auto completely?
In principle, I suppose you could, but this would at the minimum lead to parsing difficulties. e.g. in a declaration like
foo f = // ...
is foo a type, or a constraint on the type?
Whereas in the current syntax, we have
foo auto f = // ...
and there's no doubt that foo is a constraint on the type of f.
|
69,801,325 | 69,801,634 | Error: The operation completed successfully (Command Line Game Engine in C++ using Windows API) | As described in the title I want to write a game engine using the command line console. Following closely the project of oneLoneCoder, the code that I have written so far is the following. It creates a command console after it checks that the dimensions given by the user are correct.
#include <Windows.h>
#include <iostream>
#include <cassert>
namespace CmdLineConsoleEngine {
void Error(const HANDLE& hConsole, const wchar_t* msg) {
wchar_t buf[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
SetConsoleActiveScreenBuffer(hConsole);
wprintf(L"ERROR: %s\n\t%s\n", msg, buf);
exit(-1);
}
auto CreateConsole() -> HANDLE {
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
if (hConsole == INVALID_HANDLE_VALUE)
Error(hConsole, L"Bad Handle"); // in which cases does this occur?
else {
SetConsoleActiveScreenBuffer(hConsole);
}
return hConsole;
}
void CheckConsoleSize(const HANDLE& hConsole, int screenWidth, int screenHeight) {
assert(hConsole != nullptr);
assert(screenWidth > 0);
assert(screenHeight > 0);
const COORD largestSize = GetLargestConsoleWindowSize(hConsole);
if (screenWidth > largestSize.X)
Error(hConsole, L"The width dimension is too large.");
if (screenHeight > largestSize.Y)
Error(hConsole, L"The height dimension is too large.");
return;
}
void SetConsoleWindowSize(HANDLE& hConsole, int screenWidth, int screenHeight) {
CheckConsoleSize(hConsole, screenWidth, screenHeight);
const SMALL_RECT minimalRectWindow = { 0, 0, 12, 6 };
SetConsoleWindowInfo(hConsole, TRUE, &minimalRectWindow);
COORD coord = {static_cast<short>(screenWidth), static_cast<short>(screenHeight)};
if (!SetConsoleScreenBufferSize(hConsole, coord))
Error(hConsole, L"SetConsoleScreenBufferSize");
SMALL_RECT rectWindow = {0, 0, static_cast<short>(screenWidth - 1), static_cast<short>(screenHeight - 1)};
if (!SetConsoleWindowInfo(hConsole, TRUE, &rectWindow))
Error(hConsole, L"SetConsoleWindowInfo");
return;
}
void WriteToConsole(const HANDLE& hConsole, const wchar_t* screen, int screenWidth, int screenHeight) {
DWORD dwBytesWritten = 0;
WriteConsoleOutputCharacter(hConsole, screen, screenWidth * screenHeight, { 0,0 }, &dwBytesWritten);
}
}
int main() {
HANDLE hConsole = CmdLineConsoleEngine::CreateConsole();
int screenWidth = 160;
int screenHeight = 140;
CmdLineConsoleEngine::SetConsoleWindowSize(hConsole, screenWidth, screenHeight);
return 0;
}
Executing the main() function the output that I get is
ERROR: The height dimension is too large.
The operation completed successfully.
It is the Error function acting funny. For your convenience, the call hierarchy is SetConsoleWindowSize -> CheckConsoleSize -> Error
Any idea on why this happens?
| Your error reporting in CheckConsoleSize() is wrong. GetLastError() is only meaningful if GetLargestConsoleWindowSize() returns a COORD containing all zeros, which you are not checking for. What you have described sounds like the COORD is simply containing sizes that are smaller than you are expecting, but are not zeros. That is why GetLastError() is returning 0, and thus FormatMessage() is returning "The operation completed successfully".
Try something more like this instead:
#include <Windows.h>
#include <iostream>
#include <cassert>
namespace CmdLineConsoleEngine {
void Error(HANDLE hConsole, const wchar_t* msg) {
SetConsoleActiveScreenBuffer(hConsole);
wprintf(L"ERROR: %s\n", msg);
exit(-1);
}
void ErrorWithCode(HANDLE hConsole, const wchar_t* msg, DWORD ErrorCode = GetLastError()) {
wchar_t buf[256] = {};
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, ErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
SetConsoleActiveScreenBuffer(hConsole);
wprintf(L"ERROR: %s\n\t%s\n", msg, buf);
exit(-1);
}
HANDLE CreateConsole() {
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
if (hConsole == INVALID_HANDLE_VALUE)
ErrorWithCode(hConsole, L"Bad Handle"); // in which cases does this occur?
SetConsoleActiveScreenBuffer(hConsole);
return hConsole;
}
void DestroyConsole(HANDLE& hConsole) {
if (hConsole != INVALID_HANDLE_VALUE) {
CloseHandle(hConsole);
hConsole = INVALID_HANDLE_VALUE;
}
}
void CheckConsoleSize(HANDLE hConsole, int screenWidth, int screenHeight) {
assert(hConsole != INVALID_HANDLE_VALUE);
assert(screenWidth > 0);
assert(screenHeight > 0);
const COORD largestSize = GetLargestConsoleWindowSize(hConsole);
if (largestSize.X == 0 && largestSize.Y == 0)
ErrorWithCode(hConsole, L"GetLargestConsoleWindowSize");
if (screenWidth > largestSize.X)
Error(hConsole, L"The width dimension is too large.");
if (screenHeight > largestSize.Y)
Error(hConsole, L"The height dimension is too large.");
}
void SetConsoleWindowSize(HANDLE hConsole, int screenWidth, int screenHeight) {
CheckConsoleSize(hConsole, screenWidth, screenHeight);
const SMALL_RECT minimalRectWindow = { 0, 0, 12, 6 };
if (!SetConsoleWindowInfo(hConsole, TRUE, &minimalRectWindow))
ErrorWithCode(hConsole, L"SetConsoleWindowInfo");
COORD coord = {static_cast<short>(screenWidth), static_cast<short>(screenHeight)};
if (!SetConsoleScreenBufferSize(hConsole, coord))
ErrorWithCode(hConsole, L"SetConsoleScreenBufferSize");
SMALL_RECT rectWindow = {0, 0, static_cast<short>(screenWidth - 1), static_cast<short>(screenHeight - 1)};
if (!SetConsoleWindowInfo(hConsole, TRUE, &rectWindow))
ErrorWithCode(hConsole, L"SetConsoleWindowInfo");
}
void WriteToConsole(HANDLE hConsole, const wchar_t* screen, int screenWidth, int screenHeight) {
DWORD dwBytesWritten = 0;
if (!WriteConsoleOutputCharacter(hConsole, screen, screenWidth * screenHeight, {0, 0}, &dwBytesWritten))
ErrorWithCode(hConsole, L"WriteConsoleOutputCharacter");
}
}
int main() {
HANDLE hConsole = CmdLineConsoleEngine::CreateConsole();
CmdLineConsoleEngine::SetConsoleWindowSize(hConsole, 160, 140);
CmdLineConsoleEngine::DestroyConsole(hConsole);
return 0;
}
On a side note: calling Error/WithCode() if CreateConsoleScreenBuffer() fails doesn't make sense, as you would be calling SetConsoleActiveScreenBuffer() with an invalid console handle.
|
69,801,387 | 69,801,834 | How to find all the words that contain a given character the most times | Input: char (need to find the most number of occurrences of this char in words which is in array)
Output: print word which has the highest number of occurrences of given char or words if there are the same number of occurrences.
Need to find word or words which have the most number of occurrences of given char.
I wrote a program that finds and prints the word with the highest number of occurrences.
But I can't understand how to find word with given char.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char array[]="this is text. Useuuu it for test. Text for test.";
char* buf = strtok(array," .,!?;:");
char *word;
int max = 0;
char c;
while(buf) {
int n = strlen(buf);
for(int i = 0; i < n; i++) {
int counter=0;
for(int j = 0; j < n ; j++) {
if(buf[i]==buf[j] && i != j)
counter++;
if(counter>max) {
max=counter;
word=buf;
}
}
}
buf=strtok(0," .,!?;:");
}
cout << "Result: " << word << endl;
return 0;
}
In this program result is word "Useuuu"
I'm sorry for my English.
| Here is a solution to your problem that attempts to change your code the least possible:
#include <iostream>
#include <cstring>
#include <list>
using namespace std;
int main() {
char array[]="this is text. Useuuu it for test. Text for test.";
char* buf = strtok(array," .,!?;:");
std::list<const char*> words{};
int max = 0;
int wrd_counter = 0;
char c;
std::cout << "Input char: ";
std::cin >> c;
while(buf) {
int n = strlen(buf);
int counter=0;
for(int j = 0; j < n ; j++) {
if(buf[j]==c)
counter++;
}
if(counter>max) {
max=counter;
words.clear();
words.push_back(buf);
}
else if(counter == max){
words.push_back(buf);
}
buf=strtok(0," .,!?;:");
}
cout << "Results: ";
for(const char* ccp: words){
std::cout << ccp << " ";
}
return 0;
}
Explanation: In the code, instead of having a single char* word, I use a doubly-linked list to store multiple words. I iterate through each word and find the number of occurrences of the char. I then compare to see if the word belongs in the list.
Notes: this code is rough and could be optimized. Also, if the order of the words doesn't matter, you could use forward_list.
|
69,801,420 | 69,804,907 | QT Chart doesn't fill entire ChartView causing a mirroring effect | I am essentially trying to make a Gantt Chart in Qt. I was going to plot bars on a image. I am able to plot a Bar(green) starting at the beginning of a Chart but I also get a second Bar(green) closer to the end of the Chart. I think the plottable area of the Chart doesn't fill up the entire ChartView so it's doing some kind of repeated fill of the missing data(MAYBE?). Was hoping someone could tell me what I'm doing wrong. QT version 5.15.0.
ui.setupUi(parent);
QGridLayout *gridLayout = new QGridLayout(ui.widget);
//Build a series to add to the chart
QtCharts::QLineSeries *series = new QtCharts::QLineSeries();
*series << QPointF(11, 1) << QPointF(13, 3) << QPointF(17, 6) << QPointF(18, 3) << QPointF(20, 2);
//Create a chart object and format
QtCharts::QChart *chart = new QtCharts::QChart();
chart->legend()->hide();
chart->addSeries(series);
chart->createDefaultAxes();
chart->axes(Qt::Vertical).first()->setGridLineVisible(false);
chart->axes(Qt::Horizontal).first()->setGridLineVisible(false);
// ===== CHART VIEWER ===== //
// Create a Chart Viewer:
QtCharts::QChartView* chartView = new QtCharts::QChartView();
// Add widget to GUI:
gridLayout->addWidget(chartView);
//Add the chart to the view widget
chartView->setChart(chart);
chartView->setRenderHint(QPainter::Antialiasing, true);
//Note: Since we added the chart to the view we can now
//scale and translate the image appropriately. The chart
//has an appropriate size.
//Grab the size of the plot and view areas
chart->setPlotArea(QRectF());
int width = static_cast<int>(chart->plotArea().width());
int height = static_cast<int>(chart->plotArea().height());
int ViewW = static_cast<int>(chartView->width());
int ViewH = static_cast<int>(chartView->height());
//We have to translate the image because setPlotAreaBackGround
//starts the image in the top left corner of the view not the
//plot area. So, to offset we will make a new image the size of
//view and offset our image within that image with white
QImage translated(ViewW, ViewH, QImage::Format_ARGB32);
translated.fill(Qt::gray);
QPainter painter(&translated);
QPointF TopLeft = chart->plotArea().topLeft();
QPointF BotRight = chart->plotArea().bottomRight();
painter.fillRect(TopLeft.x(), TopLeft.y(), 10, BotRight.y() - TopLeft.y(), Qt::green);
//Display image in background
chart->setPlotAreaBackgroundBrush(translated);
chart->setPlotAreaBackgroundVisible(true);
| I made the 2 changes:
paint the background in a slot function.
emit the slotAreaChanged signal.
Here is the code
#include<QGridLayout>
#include<QLineSeries>
#include<QChartView>
#include<QChart>
#include<QApplication>
int main()
{
int a = 0;
QApplication b(a, nullptr);
QWidget w;
QGridLayout* gridLayout = new QGridLayout();
//Build a series to add to the chart
QtCharts::QLineSeries* series = new QtCharts::QLineSeries();
*series << QPointF(11, 1) << QPointF(13, 3) << QPointF(17, 6) << QPointF(18, 3) << QPointF(20, 2);
//Create a chart object and format
QtCharts::QChart* chart = new QtCharts::QChart();
chart->legend()->hide();
chart->addSeries(series);
chart->createDefaultAxes();
chart->axes(Qt::Vertical).first()->setGridLineVisible(false);
chart->axes(Qt::Horizontal).first()->setGridLineVisible(false);
// ===== CHART VIEWER ===== //
// Create a Chart Viewer:
QtCharts::QChartView* chartView = new QtCharts::QChartView();
// Add widget to GUI:
gridLayout->addWidget(chartView);
//Add the chart to the view widget
chartView->setChart(chart);
chartView->setRenderHint(QPainter::Antialiasing, true);
//Note: Since we added the chart to the view we can now
//scale and translate the image appropriately. The chart
//has an appropriate size.
//Grab the size of the plot and view areas
chart->setPlotArea(QRectF());
QObject::connect(chart, &QtCharts::QChart::plotAreaChanged, [&](const QRectF& plotArea) {
int width = static_cast<int>(chart->plotArea().width());
int height = static_cast<int>(chart->plotArea().height());
int ViewW = static_cast<int>(chartView->width());
int ViewH = static_cast<int>(chartView->height());
//We have to translate the image because setPlotAreaBackGround
//starts the image in the top left corner of the view not the
//plot area. So, to offset we will make a new image the size of
//view and offset our image within that image with white
QImage translated(ViewW, ViewH, QImage::Format_ARGB32);
translated.fill(Qt::gray);
QPainter painter(&translated);
QPointF TopLeft = chart->plotArea().topLeft();
QPointF BotRight = chart->plotArea().bottomRight();
painter.fillRect(TopLeft.x(), TopLeft.y(), 10, BotRight.y() - TopLeft.y(), Qt::green);
//Display image in background
chart->setPlotAreaBackgroundBrush(translated);
chart->setPlotAreaBackgroundVisible(true);
});
w.setLayout(gridLayout);
chart->plotAreaChanged(QRectF());
w.show();
return b.exec();
}
|
69,801,719 | 69,801,777 | Valgrind and ostream operator | Why is Valgrind showing error in this code?
// const char * constructor
String::String(const char* s) {
size = 0;
while(s[size] != '\0')
++size;
capacity = 0;
str = new char[size];
for (int i = 0; i < size; ++i) {
str[i] = s[i];
if (size > capacity && capacity == 0) {
++capacity;
} else if ((size > capacity && capacity != 0)) {
capacity *= 2;
}
}
}
// overloading the ostream operator
std::ostream &operator<<(std::ostream &os, const String& other) {
return std::operator<<(os, other.str);
}
// testing
TEST(Iostream, Out) {
std::stringstream os;
String s = "lol";
os << s;
ASSERT_EQ(os.str(), "lol");
}
// main function for testing
int main() {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
////////////////////////////////////////////////////////////////
Why is strlen showing here if I haven't used it anywhere?
==11274== Invalid read of size 1
==11274== at 0x48425F4: strlen (vg_replace_strmem.c:469)
==11274== by 0x49BCBCD: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
|
Why is strlen showing here if I haven't used it anywhere?
return std::operator<<(os, other.str);
This is the same function that is called when you do:
void foo(std::ostream& stream, const char * ptr) {
stream << ptr;
}
How else is the stream supposed to know the length of the passed null-terminated string if not via a strlen() or something equivalent?
|
69,802,357 | 69,802,446 | convert enum class too std::tuple | I would like to be able to create a std::tuple based on the enum value passed as a template argument, if possible without using global variables.
#include <tuple>
enum class Type
{
eInt,
eFloat,
eDouble
};
template <Type... type>
class Test
{
public:
private:
std::tuple < ? > m_data;
};
int main()
{
Test<Type::eDouble, Type::eInt> t1; // m_data = std::tuple<double, int>
Test<Type::eInt, Type::eFloat> t2; // m_data = std::tuple<int, float>
}
| Step one, figure out how to convert one constant to a type:
template <Type> struct MakeType {};
template <> struct MakeType<Type::eInt> {using type = int;};
template <> struct MakeType<Type::eFloat> {using type = float;};
// ...
This lets you do e.g. MakeType<Type::eInt>::type to get an int.
Now you can do std::tuple<typename MakeType<T>::type...> (where T is the template parameter pack, renamed from type for clarity).
|
69,802,392 | 69,802,482 | Why is the Dereference operator used to declare pointers? | Why is the * used to declare pointers?
It remove indirection, but doesn't remove any when you declare a pointer like int *a = &b, shouldn't it remove the indirection of &b?
| Many symbols in C and C++ are overloaded. That is, their meanings depend on the context where they are used. For example, the symbol & can denote the address-of operator and the binary bitwise AND operator.
The symbol * used in a declaration denotes a pointer:
int b = 10;
int *a = &b,
but used in expressions, when applied to a variable of a pointer type, denotes the dereference operator, for example:
printf( "%d\n", *a );
It also can denote the multiplication operator, for example you can write:
printf( "%d\n", b ** a );
that is the same as
printf( "%d\n", b * *a );
Similarly, the pair of square braces can be used in a declaration of an array, like:
int a[10];
and as the subscript operator:
a[5] = 5;
|
69,802,578 | 69,802,937 | how to return the number of words in the string "sentence" | I am new to coding and I want to know how to count the number of words, in the "sentence". This function uses a class, what variable should I use to return? Do I have to increment "i" to move to the next character?
int Directive::words(const char* sentence) {
int i, word = 0;
for (i = 0; sentence[i] != '\0'; i++) {
if ((sentence[i] >= 'a' && sentence[i] <= 'z') || (sentence[i] >= 'A' && sentence[i] <= 'Z')) {
i++;
if (sentence[i] != ' ' && sentence[i] != '\n' && sentence[i] != '\t') {
word++;
i++;
}
}
else
return 0;
}
return word;
}
| The sentence must end with a '\0'
#include <iostream>
using namespace std;
int GetWordsCount(const char * Sentencee){
int Count = 0;
int LetterCount = 0;
while (*Sentencee++){
if (isspace(*Sentencee) || *Sentencee == '.' || *Sentencee == ',' || *Sentencee == '\0'){
if (LetterCount)
Count++;
LetterCount = 0;
}
else
LetterCount++;
}
return Count;
}
int main()
{
const char * Sentencee = "Hello, i am learning c++!";
cout << "Sentence: " << Sentencee << endl;
cout << "count: " << GetWordsCount(Sentencee) << endl;
return 0;
}
|
69,803,296 | 69,803,674 | Overloading istream operator | I have a String class. I want to overload operator >>. Found the following way, but as far as I understand, the zero character is not added at the end (line terminator). How can I write a good operator >>?
class String {
public:
char* str;
size_t size;
size_t capacity;
~String();
String(const char*);
friend std::istream& operator>>(std::istream&, String&);
};
std::istream& operator>>(std::istream& is, String& obj) {
is.read(obj.str, obj.size);
return is;
}
| Let's start with the obvious part: your operator>> needs to actually create a valid String object based on the input you read. Let's assume you're going to read an entire line of input as your string (stopping at a new-line, or some maximum number of characters).
For the moment, I'm going to assume that the str member of any String is either a null pointer, or a pointer to data that's been allocated with new.
std::istream &operator>>(std::istream &is, String &obj) {
static char buffer[max_size];
is.getline(buffer, max_size);
std::size_t size = std::strlen(buffer);
if (size > 0) {
if (size > obj.size) {
delete [] obj.str;
obj.str = new char [size+1];
obj.capacity = size;
}
strcpy(obj.str, buffer);
obj.size = size;
}
return is;
}
That isn't intended to handle every corner case (e.g., it has no error handling), but at least gives sort of the general idea--you'll need to read in the text, check that you have enough space to store the text, allocate more if needed, copy the text into the (existing or newly allocated) space, and update at least the size to the current size, and if you reallocated, the capacity to the updated capacity as well.
|
69,803,425 | 69,803,450 | C++ should I use forwarding references? | I have functions that take values and pass them to other functions. Nobody down the chain will ever care if it's an rvalue reference and they just want to read the value. Do I need to use forwarding references or can I just use const& like this?
template<class Arg>
void printOne(std::string& str, std::string_view fmt, const Arg& arg) {
if constexpr (std::is_same<char, Arg>::value) {
// ...
} else if constexpr (...) {
// ...
}
}
template<class ...Args>
std::string printFormatted(std::string_view fmt, const Args& ...args) {
std::string str;
(printOne(str, fmt, args), ...);
return str;
}
| No, you don't have to use forwarding references. const references bind to temporary rvalues, so in general when move semantics or perfect forwarding is not required, a plain, garden-variety const reference will work.
|
69,803,659 | 69,808,412 | What is the proper way to build for macOS-x86_64 using cmake on Apple M1 (arm)? | I'm using a library that I cannot compile for Apple M1, so I have decided to compile it and use it using (Rosetta 2) for x86_64 which I successfully did following this to install brew and clang for x86_64.
However when I compile my project and try to link it against this library I get this error:
ld: warning: ignoring file ..../libapronxx.a, building for macOS-arm64 but attempting to link with file built for macOS-x86_64
...
ld: symbol(s) not found for architecture arm64
I have tried to the set compiler and linker flags ("-arch x86_64") but still got the same problem.
My question is: What is the proper way to build for macOS-x86_64 using cmake on Apple M1 (arm)?
Additional information: I'm using cmake via CLion.
UPDATE:
I successfully compiled my project using the following commands:
# install a x86 cmake
arch -x86_64 /usr/local/bin/brew install cmake
...
# in the build directory
arch -x86_64 /usr/local/bin/cmake ..
make
arch -x86_64 ./my_exe
I also specified the architecture for clang using -arch flag
string(APPEND CMAKE_CXX_FLAGS_RELEASE " -arch x86_64 -O3")
string(APPEND CMAKE_CC_FLAGS_RELEASE " -arch x86_64 -O3")
# did the same for debug too
While this work fine, I still don't believe it is the proper way to use cmake to build for macOS-x86_64, in fact I cannot take the advantages of my IDE with all this manual approach.
| After checking CMake source code, I found that it is enough to set CMAKE_OSX_ARCHITECTURES to x86_64:
set(CMAKE_OSX_ARCHITECTURES "x86_64")
This is the cleanest way so far to solve this issue, and work straight forward with CLion too.
|
69,804,017 | 69,804,107 | Why are function calls in this parameter pack evaluated backwards? | Recently I found this StackOverflow answer about unrolling a loop with templates. The answer states that "the idea is applicable to C++11", and I ended up with this:
namespace tmpl {
namespace details {
template<class T, T... values>
class integer_sequence {
public:
static constexpr size_t size() { return sizeof...(values); }
};
template<class T, class N, class... Is>
struct make_integer_sequence_helper :
make_integer_sequence_helper<T, std::integral_constant<T, N::value - 1>, std::integral_constant<T, N::value - 1>, Is...> {};
template<class T, class... Is>
struct make_integer_sequence_helper<T, std::integral_constant<T, 0>, Is...> {
using type = integer_sequence<T, Is::value...>;
};
template<class T, T N>
using make_integer_sequence = typename make_integer_sequence_helper<T, std::integral_constant<T, N>>::type;
template<class... Ts>
void variadic_noop(Ts... params) {}
template<class F, class T>
int call_and_return_0(F&& f, T i) {f(i); return 0;}
template<class T, T... Is, class F>
void loop(integer_sequence<T, Is...>, F&& f) {
variadic_noop(call_and_return_0(f, Is)...);
}
}
template<class T, T max, class F>
void loop(F&& f) {
details::loop(details::make_integer_sequence<T, max>{}, f);
}
}
Let's take a simple example of how this template would be used:
tmpl::loop<size_t, 20>([&](size_t idx) {
cout << "Loop " << idx << std::endl;
});
When I use the C++17 code from the other answer, it iterates from 0 up to 19. However, the C++11 jank I've written iterates from 19 down to 0.
In theory, when details::loop() is expanded it should become something like this:
variadic_noop(call_and_return_0(f, 0), call_and_return_0(f, 1), call_and_return_0(f, 2), ...);
So, why does C++ run call_and_return_0(f, 19) first if it's the last parameter to variadic_noop()?
| The evaluation of function arguments in a function call may be from left to right, right to left, or any other order, which is not required to be predictable.
However, when you have a single expression of the form e_1, e_2, ..., e_n where the subexpressions e_1, e_2, ..., e_n are separated by comma operators, then the subexpressions will always be evaluated in left-to-right order, because the comma operator guarantees that its left operand is evaluated before its right operand. (Prior to C++17, this guarantee only holds for the built-in comma operator, and not for any overloaded ones.)
Although function calls also use commas, the commas in a function call do not enforce left-to-right evaluation. The code from the linked answer uses C++17 fold expressions to create a sequence of expressions separated by comma operators.
|
69,804,068 | 69,804,116 | Convert C++ for loop to python | I am new to python. So, I converted C++ for loop to python. Please check if I have done it correctly. If not, then please inform me how to do it. If I am correct, then please inform me if there's any better and optimized way to do it.
C++ Code:
void printunorderedPairs(int[] array) {
for (int i=0; i<array.length;i++){
for (int j=i+1; j<array.length;j++){
System.out.println(array[i] + "," + array[j]);
}
}
}
My Python Code:
i=0
while i<len(array):
j=i+1
while j<len(array):
print(array[1],arr[2])
j=j+1
i=i+1
| In python it's more idiomatic to use for loops, and you can use an array slice for the inner loop.
for i, el1 in enumerate(array):
for el2 in array[i+1:]:
print(el1, el2)
|
69,804,246 | 69,804,316 | "Red Heart ❤️" unicode character in ncurses | Currently using WSL2, C++20, with the preprocessor directives #define _XOPEN_SOURCE_EXTENDED 1, #include <panel.h>, and flags -lpanelw -lncursesw.
Using the code provided below when I try to add the "Red Heart ❤️" character in ncurses, it causes weird bugs on the terminal window, especially when I encase it with a box. I've gotten the same problem on my MacBook as well. When I put the unicode character in a string "❤️", it gives me a const char[7], as opposed to many other unicode characters that give a const char[5]. Could this have something to do with the cause of the bugs? I would really appreciate it if someone could give me some insight into this problem.
(Ignore the cursor at the bottom right of some of the pictures, that's just a cursor problem with the terminal in VS Code).
1 Red Heart:
2 Red Hearts:
2 Purple Hearts:
Code:
#define _XOPEN_SOURCE_EXTENDED 1
#include <panel.h>
#include <iostream>
int main() {
setlocale(LC_ALL, "");
initscr();
raw();
noecho();
curs_set(0);
refresh();
WINDOW *win {newwin(8, 16, 10, 10)};
box(win, 0, 0);
mvwaddwstr(win, 1, 1, L"❤️");
mvwaddwstr(win, 1, 5, L"❤️");
wrefresh(win);
getch();
endwin();
}
| The "character" "❤️" you are using is not actually a single character. It is composed of two Unicode characters, "❤"(U+2764) and a modifying U+FE0F, "VARIATION SELECTOR-16" which gives the red style of the emoji.
You can verify the encoded form of a string by typing echo -n ❤️ | hexdump -C in WSL console, which should output
00000000 e2 9d a4 ef b8 8f |......|
00000006
Or with Python,
In [1]: heart="❤️"
In [2]: len(heart)
Out[2]: 2
In [3]: hex(ord(heart[0]))
Out[3]: '0x2764'
In [4]: hex(ord(heart[1]))
Out[4]: '0xfe0f'
More about Variation Selectors.
|
69,804,387 | 69,874,543 | Bones rotate around parent - OpenGL Animation/Skinning | I am having an issue with my bone skinning where instead of my bones rotating around their local origin, they instead rotate around the their parent. Left - my engine. Right - blender
There are two locations in the pipeline that I suspect are at fault, but I cant tell where exactly it is. First, I have this bit of code that actually calculates the bone matrices:
void CalculateBoneTransform(DSkeletonBone sb, dmat4x4f parentTransform, std::vector<DSkeletonBone> boneOverrides)
{
if (boneDataIndex.count(sb.name) == 0) return;
Transform transform = sb.localTransform;
for (auto& bo : boneOverrides)
{
if (bo.name == sb.name)
{
transform = bo.localTransform;
}
}
dmat4x4f globalTransform = dmat4x4f::Mul(parentTransform, transform.GetMatrix());
dmat4x4f finalTransform = dmat4x4f::Mul(globalTransform, sb.inverseTransform);
finalTransforms[boneDataIndex[sb.name]] = finalTransform;
for (auto& pbC : sb.children)
{
CalculateBoneTransform(pbC, globalTransform, boneOverrides);
}
}
The boneOverrides come from anything that would like to override a bone (such as an animation).
finalTransforms is the array that is pushed to the shader.
In my mesh/anim parser, I have this code that calculates the inverse bind pose matrices (using OpenFBX, but this is not relevant):
glm::mat4 local = glm::inverse(GetMatFromVecs(
boneData[skin->getCluster(i)->name].pos,
boneData[skin->getCluster(i)->name].rot,
boneData[skin->getCluster(i)->name].scl));
for (Object* parent = skin->getCluster(i)->getLink()->getParent(); parent != NULL; parent = parent->getParent())
{
glm::mat4 parentInverseTransform = glm::inverse(GetMatFromVecs(
parent->getLocalTranslation(),
parent->getLocalRotation(),
parent->getLocalScaling()));
local = parentInverseTransform * local;
}
boneData[skin->getCluster(i)->name].offset = local;
The getLocalXX functions get the item in local space.
And the GetMatFromVecs function referenced above:
glm::mat4 GetMatFromVecs(Vec3 pos, Vec3 rot)
{
glm::mat4 m(1);
m = glm::scale(m, glm::vec3(1,1,1));
m = glm::rotate(m, (float)rot.x * 0.0174532925f, glm::vec3(1, 0, 0));
m = glm::rotate(m, (float)rot.y * 0.0174532925f, glm::vec3(0, 1, 0));
m = glm::rotate(m, (float)rot.z * 0.0174532925f, glm::vec3(0, 0, 1));
m = glm::translate(m, glm::vec3(pos.x, pos.y, pos.z));
return m;
}
Notice I am rotating first, then translating (this is also the case with the GetMatrix() function referenced in the first snippit, by the way).
So my question is, why is this happening? Also, what are some causes of this type of thing in mesh skinning? My translations are local, but rotations are not.
| My issue was bad matrix math. I swapped out my matrix::mul function for glm's and got intended results.
|
69,804,675 | 69,804,781 | 'go' was not declare in this scope (C++) | I've tried declaring but still wrong and I've tried several other ways but still error, Can you help me?Sorry I new to Programming
'go' not declare in this scopewhat do i have to do?
this code
#include <iostream>
#include <stdio.h>
#include <conio.h>
void push (void);
void pop (void);
void gotoxy(int x, int y);
int x, top;
int s [5], N=5;
main()
{
char pilih;
char barloop;
system ("cls");
gotoxy ( 25,7 ); puts ("coba stack"); ;
gotoxy ( 25,10 ); puts ("1. push");
gotoxy ( 25,13 ); puts ("2. pop");
gotoxy ( 25,16 ); puts ("3. exit");
gotoxy ( 25,19 ); printf("Pilih :");
scanf (" %x " , &pilih);
switch(pilih)
{
case 1: printf ("\n masukkan data x=;"),
scanf (" "); push(); getch(); break;
case 2: pop (); getch(); break;
case 3: exit(0);
}
go to char barloop;
}
void pop (void)
{
if (top > 0)
{
}
else { printf("\n\r stack kosong"); }
}
thank you
|
First of all, there is no go to keyword in C++. It's goto with no space.
Second, your goto sentence isn't right in syntax. goto syntax looks like this:
dothisagian: // this is a statement label
// code
goto dothisagian;
It doesn't magically jump into what line you wrote. It jumps to the statement label.
Third, you have to write what return value main() is.
So, your code should look like this:
int main() // main returns an int
{
doThisAgain:
char barloop;
// code
goto doThisAgain;
}
One last note: You shouldn't really use goto in C++ unless necessary. You should use one of the three types of loops instead.
|
69,805,021 | 69,806,864 | How to remove duplicates from vector by iteratting though? | I'm doing an assignment for my computer engineering class where we have to remove duplicates from a vector. I found solutions elsewhere, but I can't figure out how to iterate through without including the algorithm library
#include <vector>
using namespace std;
vector<int> deleteRepeats(const vector<int>& nums); // Declaration
void print(const vector<int>& nums);
int main() {
vector<int> nums;
vector<int> res;
// Test 1
nums = {1, 2, 3, 3, 2};
res = deleteRepeats(nums);
print(res); // Should print 1, 2, 3
// Test 2
nums = {-1, 2, 4};
res = deleteRepeats(nums);
print(res); // Should print -1, 2, 4
// Test 3
nums = {42, 42, 42,};
res = deleteRepeats(nums);
print(res); // Should print 42
// Test 4
nums = {};
res = deleteRepeats(nums);
print(res); // Should print a blank
return 0;
}
vector<int> deleteRepeats(const vector<int>& nums) {
vector<int> res;
bool foundRepeat;
//my code here
return res;
}
void print(const vector<int>& nums) {
for (int i = 0; i < nums.size(); i++)
cout << nums[i] << " ";
cout << endl;
}
| So, the requirement is to not use the algorithm library and do it manually.
Also no problem, because your teacher gave you already a strong hint by writing:
vector<int> deleteRepeats(const vector<int>& nums) {
vector<int> res;
bool foundRepeat;
//my code here
return res;
}
You have an input vector nums and a result vector res. Obviously you need to copy values from the input vector to the resulting vector. But no duplicates.
The solution is to
iterate all numbers in the input vector nums
and then compare each number with all numbers in the resulting vector res
and if youd could not find a repeat (foundRepeat), copy the value into the resulting vector.
You need 2 loops. The outer loop will read all values from the input vector nums. Each of this value will be compared with all existing values in the res vector. For this we create an inner llop and iterate over all existing values in the res vector. If the number from the outer loop is equal to the value from the inner loop, then we have obviously a duplicate. We will not add the value. If we do not have a duplicate, then we add the number from the outer loop to the res vector.
This could then look for example like the below:
#include <iostream>
#include <vector>
using namespace std;
vector<int> deleteRepeats(const vector<int>& nums); // Declaration
void print(const vector<int>& nums);
int main() {
vector<int> nums;
vector<int> res;
// Test 1
nums = { 1, 2, 3, 3, 2 };
res = deleteRepeats(nums);
print(res); // Should print 1, 2, 3
// Test 2
nums = { -1, 2, 4 };
res = deleteRepeats(nums);
print(res); // Should print -1, 2, 4
// Test 3
nums = { 42, 42, 42, };
res = deleteRepeats(nums);
print(res); // Should print 42
// Test 4
nums = {};
res = deleteRepeats(nums);
print(res); // Should print a blank
return 0;
}
vector<int> deleteRepeats(const vector<int>& nums) {
vector<int> res;
bool foundRepeat;
//my code here
// Iterate over all nums
for (unsigned int i = 0; i < nums.size(); ++i) {
// Get current num at index i
int num = nums[i];
// Here we will indicate, if we found a duplicate
foundRepeat = false;
// Now search, if this num is already in the result vector
for (unsigned int k = 0; (k < res.size() && !foundRepeat); k++) {
// This is the number in the res vector at the current index
int numInRes = res[k];
// Check for a repeating (duplicate value)
if (numInRes == num) {
// Remeber that we found a duplicate and also stop the loop
foundRepeat = true;
}
}
// If no duplicate has been found, then add the num to the result
if (!foundRepeat) res.push_back(num);
}
return res;
}
void print(const vector<int>& nums) {
for (int i = 0; i < nums.size(); i++)
cout << nums[i] << " ";
cout << endl;
}
|
69,805,476 | 69,817,060 | Probably a simple question about a c++ loop | I would like to start off by thanking everybody that attempts to help give me guidance through this issue. I am creating a snake clone to give myself real problems and situations. I have gotten through a lot on my own but unfortunately I have felt like I hit a brick wall and don't want to waste anymore time not understanding something that is probably really simple.
My issue is with the tail of the snake. When I create a block of the snakes tail I want that block to take the position of the pervious block that was created. This is because as of right now the first block follows the head which is not in the same class. The head is referred to as the playerObj in the code. I created a for loop because I thought that would be the best way to get this done and I excluded the first block of tail from the for loop.
for (int i = 1; i < snakeSize; i++)
int previousTail = i - 1;
//std::cout << "CURRENT TAIL X: " << CurTailPosX << " Y: " << CurTailPosY << std::endl;
// This is the where the issue happens - ONLY TAIL 0 POS IS TRACKED AND ALL OTHERS GET UPDATED TO ITS POS
growTail.snakeArray[i][0] = growTail.snakeArray[previousTail][0];
growTail.snakeArray[i][1] = growTail.snakeArray[previousTail][1];
std::cout << "Last Tail Pos X: " << growTail.snakeArray[previousTail][0] << " Y: " << growTail.snakeArray[previousTail][1] << std::endl;
Currently what is happening is all of the tails that get created end up just becoming the first tail blocks position so they all appear as one block which of course is the first tail block. I am sure this is very simple and again sorry for that but I am learning after-all.
If that's not enough information you can check out this paste bin link that will have the whole file you can look through (https://pastebin.com/zSJCVJ9F). Thanks again for reading this far in and dealing with me lol...
| What the posted code is doing is basically the following
for (size_t i = 1; i < a.size(); i++)
{ // Given a container, e.g. {1, 2, 3, 4}
a[i] = a[i - 1]; // the result would be {1, 1, 1, 1}
}
You should traverse the container in the opposite direction to preserve its values other than the last one.
Given the task, I'd suggest to implement a circular buffer or use std::deque:
The complexity (efficiency) of common operations on deques is as follows:
Random access - constant O(1)
Insertion or removal of elements at the end or beginning - constant O(1)
|
69,805,553 | 69,805,659 | How to constraint a template to be iterable ranges using concepts? | Say I have some template function that returns the median of some iterable object passed into it.
Something like:
template<typename T>
decltype(auto) find_median_sorted(T begin)
{
// some code here
}
Now I want to make sure I constrained T to always be iterable. I am trying to learn how to use concepts in C++, so is there some way I can use concept here to make sure T is iterable?
I'm sure there are other ways to check if it is iterable, but is this a wrong use case for concepts?
I also came across this post here related to element iterable, but I am not sure how this applies to my case.
|
I am trying to learn how to use concepts in C++, so is there some way I can use concept here to make sure T is iterable?
You can have standard concept std::ranges::range from <ranges> header here. With that your function will look like:
#include <ranges> // std::ranges::range
template<std::ranges::range T>
decltype(auto) find_median_sorted(T const& container) {
// some code here
}
To restrict the ranges to be only for random access iterable ranges, you can use either std::ranges::random_access_range again from <ranges> header
#include <ranges> // std::ranges::random_access_range
template<std::ranges::random_access_range T>
decltype(auto) find_median_sorted(T const& container) {
// some code here
}
or via iterator concept std::random_access_iterator
as follows:
#include <iterator> // std::random_access_iterator
template<typename T>
decltype(auto) find_median_sorted(T const& container)
requires std::random_access_iterator<std::ranges::iterator_t<T>>
{
// some code here
}
|
69,805,789 | 69,929,939 | How to run Yolov5 tensorflow model.pb inside c++ code? |
I have trained a model using yolov5 and I got the model.pt I convert
it using the export file to TensorFlow compatible model.pb now I want
to use this model with c++ instead of python I did a lot of research
but I did configure it out how to do this, so where can I find an
example that uses model.pb inside c++ code?
I tried running the model.pt using TochScript it worked fine I tried
running the model.onnx it runs but slow now I'm trying to run the
mode.pb
| I did not find a way to run model.pb directly but after a long research I've been able to run the saved_model. There are the important lines of the code
// the input node is:
const string input_node = "serving_default_input_1:0";
// the output node is:
std::vector<string> output_nodes ={"StatefulPartitionedCall:0"};
tensorflow::SavedModelBundle bundle;
//std::string path = path to the saved model folder ./yolov5s_saved_model/
tensorflow::LoadSavedModel(session_options, run_options, path, {"serve"},
&bundle);
std::vector<std::pair<string, Tensor>> inputs_data = {{input_node, image_output}};
std::vector<tensorflow::Tensor> predictions;
bundle.GetSession()->Run( inputs_data , output_nodes, {}, &predictions);
|
69,806,067 | 69,806,168 | Is a parameter name neccesary for virtual method definition in C++? | Here is the code:
virtual bool myFunction(const Waypoints& /*waypoints*/) {
return false;
}
For my understanding, virtual function is for late / dynamic binding. bool is the return type. const Waypoint& is a constant reference. When it is used to formal parameters, it avoids value copy and forbids being changed by the function.
Now, my question is, shall we need a variable name for the formal parameter of this function somehow? I mean, /*waypoints*/ are simply comments, right? Where are the formal parameters then?
| The method has one formal parameter of type const Waypoints&. It is unnamed, because it is not used in the method body. This might make sense, because other implementations of the same method might use it (note that the method is virtual). Whether the name of the parameter /*waypoints*/ is commented out, left there or removed altogether is a matter of taste. Some compilers issue a warning when a formal parameter (that does have a name) is not used in the method body, so this might be the reason it was commented out.
|
69,806,193 | 69,806,264 | Problems to understand the size of malloc parameter | Can anyone explain how does below code work? Cuz I found myself don't know what |malloc(inputNim+1)andexit(1)` stands for in below code...
buffer = (char*) malloc (inputNum+1);
if (buffer==NULL) exit (1);
| This line tries to allocate inputNum + 1 bytes of memory:
buffer = (char*) malloc (inputNum+1);
The below line checks if the above allocation succeeded. If malloc fails, it returns nullptr (NULL) and the decision is then to exit the program with return value 1. A common convention is to exit with 0 on success and something else on failure.
if (buffer==NULL) exit (1); // if allocation failed, end program
|
69,807,116 | 69,807,184 | Can not-copyable class be caught by value in C++? | In the next program, struct B with deleted copy-constructor is thrown and caught by value:
struct B {
B() = default;
B(const B&) = delete;
};
int main() {
try {
throw B{};
}
catch( B ) {
}
}
Clang rejects the code with an expected error:
error: call to deleted constructor of 'B'
catch( B ) {
However GCC accepts the program finely, demo: https://gcc.godbolt.org/z/ed45YKKo5
Which compiler is right here?
| Clang is correct. (Thanks for @NathanOliver's comments.)
[except.throw]/3
Throwing an exception copy-initializes ([dcl.init], [class.copy.ctor]) a temporary object, called the exception object. An lvalue denoting the temporary is used to initialize the variable declared in the matching handler ([except.handle]).
[except.throw]/5
When the thrown object is a class object, the constructor selected for the copy-initialization as well as the constructor selected for a copy-initialization considering the thrown object as an lvalue shall be non-deleted and accessible, even if the copy/move operation is elided ([class.copy.elision]).
The exception object is considered as an lvalue, in the copy-initialization of the parameter of the catch clause, the copy constructor is selected. The copy operation might be elided as an optimization; but the copy constructor still has to be present and accessible.
I've reported this as gcc bug 103048.
BTW the copy-initialization of the exception object caused by throw B{}; is fine because of mandatory copy elision (since C++17).
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:
T x = T(T(f())); // only one call to default constructor of T, to initialize x
First, if T is a class type and the initializer is a prvalue expression whose cv-unqualified type is the same class as T, the initializer expression itself, rather than a temporary materialized from it, is used to initialize the destination object: see copy elision (since C++17)
|
69,807,142 | 69,807,220 | Why Eigen doesn't need template keywords for using template function call of Matrix? | MWE with c++17 and Eigen 3.4.0
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
Matrix<float, 2, 2> m;
m << 1.0, 2.0, 3.0, 4.0;
m.cast<double>();
// m.template cast<double>();
return 0;
}
After reading Eigen document TopicTemplateKeyword and
popular SO answer where-and-why-do-i-have-to-put-the-template-and-typename-keywords
I kinda know why/when we need template keywords. However, now I don't understand why the code above doesn't emit error message when I forget use template:
m.cast<double>();
Looks like it matches each rule of "have to use template" in the Eigen document.
m is a dependent name
cast is a member template
Why Eigen doesn't force me to add template before calling cast?
My best guess is m might not be a real dependent name(I could be wrong). It would be nice if someone could show me the source code line. I feel this is a nice FEATHER and I wanna write similar code as an author so that makes my user's life easier.
| m is not a dependent name.
You can only have dependent names inside of a template, if they depend on the template parameters of the enclosing templates.
Example:
template <typename T>
void foo()
{
Matrix<T, 2, 2> m; // Note that `T` has to be involved.
m << 1.0, 2.0, 3.0, 4.0;
m.template cast<double>();
}
|
69,807,205 | 69,808,959 | How to cast a QML object as QQuickWindow from c++ code? | I am using QQmlVTKPlugin, which allows me to directly access to VTKRenderWindow and VTKRenderItem with QML. To setup this I need to give to my QQMLApplicationEngine a QQuickWindow and a QQuickItem. If I just do this initialization from the main.cpp everything works correctly but for some reason I need to do that by calling a class constructor inside my QML file with a singleton. I call the following constructor from the QML but when I do window->show() my application crashes
SceneManage::SceneManage(QObject *topLevel)
{
window = qobject_cast<QQuickWindow *>(topLevel); // QQuickWindow window
window->show();
QQuickItem *item = topLevel->findChild<QQuickItem *>("3DViewer");
...
Does someone have a way to do what I want ?
| Solution : Don't decide to show the window from c++ but only set visible parameter in QML.
|
69,807,222 | 69,807,365 | Adding comment in raw string literal | I have a raw string literal:
const char* s1 = R"foo(
Hello
World
)foo";
I would like to add a comment inside this string literal, e.g.:
const char* s1 = R"foo(
Hello
// Say hello to the whole world because we don't know who will run the program.
World
)foo";
This comment is actually used as part of the string. Is there any way to escape this comment to be parsed as an actual comment (or does that defeat the purpose of a raw string)?
I can obviously do ugly things like split the string in two add a comment between the two parts and concatenate them but I am looking for something more elegant.
| I think the closest thing is to "escape it" with the raw string end and start delimiters:
const char* s1 = R"foo(
Hello)foo"
// Say hello to the whole world because we don't know who will run the program.
R"foo(
World
)foo";
|
69,807,478 | 69,807,784 | How do you connect to a server and login trough console in C++? | So lets say I want to connect to a website and I want to login to the website without accessing it using a search engine. Can someone tell me how I should do that and what libraries to use using C++? Thanks.
| i.e. if you want to log into your gmail, you'll need Gmail's login API from their website.
Try and look in the communications sections of this website to find what you need :
https://en.cppreference.com/w/cpp/links/libs
Once you've downloaded the most suitable library for you, do these steps:
Make sure you have a valid internet / ethernet connection,
Find the exact API call to login to the account,
Make sure you have the correct authorisation to log into the account.
You're connected.
|
69,807,502 | 69,807,728 | Type deduction for lamda wrapped in template function | I implemented custom alternative of std::bind version like below:
template <typename F, typename ... Ts>
constexpr auto curry(F &&f, Ts ... args) {
return [&](auto&& ... args2) {
return f(std::forward<Ts...>(args...), args2...);
};
}
This function gets function and pack of the arguments to be applied, and returns lambda which is f with partially applied arguments args.
Also, for test this code, I have a function, which gets 2 arguments and just returns first one:
template <typename T1, typename T2>
constexpr T1 fconst(T1 &&x, T2&&) {
return x;
}
When I use my curry function like below:
int main() {
auto z2 = curry(fconst, 5);
return 0;
}
I get an error that compiler can't deduce F type:
error: no matching function for call to ‘curry(<unresolved overloaded function type>, int)’
17 | auto z2 = curry(fconst, 5);
candidate: ‘template<class F, class ... Ts> constexpr auto curry(F&&, Ts ...)’
15 | constexpr auto curry(F &&f, Ts ... args) {
| ^~~~~
note: template argument deduction/substitution failed:
note: couldn’t deduce template parameter ‘F’
17 | auto z2 = curry(fconst, 5);
But when I implement curry function as macro instead of template function:
#define curry(f, args...) \
[&](auto&& ... args2) { \
return f(args, args2...); \
};
My main code compiles successfully.
I use g++11 and c++20 enabled.
My questions are:
Why compiler can't deduce F type for template, but can do it when pass lambda as is?
Can my curry function be implemented using template function, or macro is only possible way to do it?
| First, your curry is dangerous because the lambda inside captures local arguments by reference. As soon as curry return you've got dangling refs.
Correct version is:
template <typename F, typename ... Ts>
constexpr auto curry(F &&f, Ts ... args) {
return [...args=std::move(args), f=std::forward<F>(f)](auto&& ... args2) mutable {
return std::invoke(f,args..., std::forward<decltype(args2)>(args2)...);
};
}
There are two equal styles shown by f, args handling.
Either copy the at the caller side - args.
Or copy/move (by forward) at capture time.
(Parameter pack capture is C++20). There is an uglier workaround using tuples and std::apply, ask if you need it.
std::bind never moves its captured arguments, they are always passed as lvalues to the callee. This makes repeated calls safe.
args2 should be correctly forwarded.
Unfortunately there is no macro-less solution. This is the inherent issue with sets of overloaded functions. One cannot pass such sets around, there simply is no support in C++ for that. There were some papers trying to fix that - I know of P1170R0. But none were accepted so far.
The workaround is essentially what you came up with and why your second example works - the macro is capable of pasting the function name, no matter whether it is overloaded (or what it is at all really).
#define overload_set(overloaded_f) \
[](auto&& ... args) { \
return overloaded_f(std::forward<decltype(args)>(args)...);} \
This is in-place perfect-forwarding lambda with copy-pasted overloaded_f symbol inside. Still, one cannot take an address of this(or rather shouldn't) like any other ordinary function, but it can be passed to e.g. curry.
Full example
#include <iostream>
template <typename F, typename... Ts>
constexpr auto curry(F&& f, Ts... args) {
return [... args = std::move(args),
f = std::forward<F>(f)](auto&&... args2) mutable {
return f(args..., std::forward<decltype(args2)>(args2)...);
};
}
template <typename T1, typename T2>
constexpr T1 fconst(T1&& x, T2&&y) {
std::cout<<"Value x:" << x<<'\n';
std::cout<<"Value y:" << y<<'\n';
return x;
}
#define overload_set(overloaded_f) \
[&](auto&&... args) { \
return overloaded_f(std::forward<decltype(args)>(args)...); \
}
struct Foo{
Foo()=default;
Foo(Foo&&)=default;
Foo(const Foo&)=delete;
operator int(){ return 42;}
};
int main() {
// Overloaded function can now be stored in a lambda.
auto stored_set= overload_set(fconst);
// And called as ordinary function.
auto ret =stored_set(1.0, 2.0);
std::cout<<"Returned value: " <<ret <<'\n';
// Overloaded set now can be passed around.
// But it is a functor, not a function.
auto curried_fnc= curry(overload_set(fconst),1.0);
// Curry works
auto ret2 = curried_fnc(2.0);
std::cout<<"Returned value: " <<ret2<<'\n';
// Move-only values work too.
std::cout<<"Curry move\n";
curried_fnc(Foo{});
}
Output
Value x:1
Value y:2
Returned value: 1
Value x:1
Value y:2
Returned value: 1
Curry move
Value x:1
Value y:42
|
69,807,592 | 69,807,966 | Why does returning a vector initialized with curly braces within normal brackets cause a compilation error? | I just wrote a simple method to return a vector made with two int arguments. However, when I return the initialized int vector within normal brackets, it causes compilation error.
std::vector<int> getVec(int x, int y)
{
return({x, y}); // This causes compile error
return {x, y}; // This is fine
}
The error message says:
q.cpp: In function ‘std::vector<int> getVec(int, int)’:
q.cpp:8:21: error: expected ‘;’ before ‘}’ token
8 | return({x, y});
| ^
| ;
q.cpp:8:15: error: could not convert ‘((void)0, y)’ from ‘int’ to ‘std::vector<int>’
8 | return({x, y});
| ^~~~~~~~
| |
| int
| From return statement:
return expression(optional) ; (1)
return braced-init-list ; (2)
Remember the {..} is not an expression, has no type. There exist some contexts which allow {..} to be deduced in some type.
There is a special case for return {..} (2) and uses copy-list-initialization to construct the return value of the function.
In return ({x, y}), we go in (1), and {x, y} still has no type, no special cases for ({..}). So the error.
|
69,808,012 | 69,810,307 | How to generate LLVM IR without optimization | I am writing an LLVM PASS to analyze info in registers. It seems that IRBuilder optimized my code automatically, making an expression to be an operand. For example, I write down below code to generate LLVM IR.
// %reg = getelementptr inbounds ([128 x i256], [128 x i256]* @mstk, i256 0, i256 0
std::vector<llvm::Value*> indices(2, llvm::ConstantInt::get(Type::Int256Ty, 0));
llvm::ArrayRef<llvm::Value *> indicesRef(indices);
llvm::Value* m_sp = m_builder.CreateGEP(conArray, indicesRef, "spPtr");
// store 0, *%m_sp
m_builder.CreateStore(llvm::ConstantInt::get(Type::Int256Ty, 0), m_sp);
The expected IR should consist of two registers. (see below)
%reg = getelementptr inbounds ([128 x i256], [128 x i256]* @mstk, i256 0, i256 0)
store i256 0, i256* reg
Unfortunately, IRBuilder optimizes the IR by combining the registers.
store i256 0, i256* getelementptr inbounds ([128 x i256], [128 x i256]* @mstk, i256 0, i256 0)
Is it possible to disable the IR optimization? I have made sure that I turned off all PASS. Thanks.
| I solved this problem by disabling the constant folder of IR builder. See Disable constant folding for LLVM 10 C++ API
|
69,808,364 | 69,809,011 | C++ object initialization with copy-list-initializer | // Example program
#include <iostream>
#include <string>
class T{
public:
int x, y;
T(){
std::cout << "T() constr called..." << std::endl;
};
T(int x, int y):x(x),y(y){
std::cout << "T(x,y) constr called..." << std::endl;
}
void inspect(){
std::cout << "T.x: " << this->x << std::endl;
std::cout << "T.y: " << this->y << std::endl;
}
};
int main()
{
T t1(5,6);
t1.inspect();
std::cout << std::endl;
T t2 = {};
t2.inspect();
}
I am getting the following result:
T(x,y) constr called...
T.x: 5
T.y: 6
T() constr called...
T.x: 208787120
T.y: 31385
The members of t2 instance were not zero initialized (what I wanted to achieve). Do I understand it correctly, that if I have a constructor defined, it will not perform a zero initialization?
(I know how to achieve initialization to zero using explicit default values. The problem is why I am not able to do it using the init-list)
List initialization
Otherwise, if the braced-init-list is empty and T is a class type with a default constructor, value-initialization is performed.
Value-initialization
In all cases, if the empty pair of braces {} is used and T is an aggregate type, aggregate-initialization is performed instead of value-initialization.
Aggregate-initialization (it seems this is not my case and therefore it is not initializing members to zero)
An aggregate is one of the following types:
class type (typically, struct or union), that has
no user-declared constructors
What would be the simplest and less error-prone modification of legacy code, where I need to solve issues where some class members are used before they are initialized?
|
Do I understand it correctly, that if I have a constructor defined, it will not perform a zero initialization?
Yes.
Note that T is not an aggregate because it contains user-provided constructors. As the effect of value initialization:
if T is a class type with no default constructor or with a
user-provided or deleted default constructor, the object is
default-initialized;
if T is a class type with a default constructor that is neither
user-provided nor deleted (that is, it may be a class with an
implicitly-defined or defaulted default constructor), the object is
zero-initialized and then it is default-initialized if it has a
non-trivial default constructor;
T contains a user-provided default constructor, then #1 (but not #2 performing zero-initialization firstly) is applied.
In default initialization, the user-provided default constructor is used to initialize the object. The default constructor doesn't perform initialization on data members, they are initialized to indeterminate values.
|
69,808,786 | 69,808,911 | Why are these 2 cout statements giving opposite result? | I can't understand why the statements are giving different results as According to Me
a==b is same as b==a
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
cout<<(pow(10,2)==(pow(8,2)+pow(6,2)))<<endl;
cout<<((pow(8,2)+pow(6,2))==pow(10,2))<<endl;
return 0;
}
OUTPUT IS-
1
0
| This is double comparison issue. You can use something like:
cout<<(fabs(pow(10,2) - (pow(8,2)+pow(6,2))) < std::numeric_limits<double>::epsilon() ) <<endl;
cout<<(fabs((pow(8,2)+pow(6,2))-pow(10,2)) < std::numeric_limits<double>::epsilon() ) <<endl;
Ref:
What is the most effective way for float and double comparison?
|
69,808,948 | 69,809,296 | Setting up SWV printf on a Nucleo STM32 board (C++) | I am using an STM32G431KB, which compared to other stm32 Nucleo, has the SWO wired. I found this question Setting up SWV printf on a Nucleo STM32 board and followed the first answer. Thereby, I got the SWV running under C. But as soon as I switch to C++, there is no output.
I used a new project for C, switched Debug to "Trace Asynchronous SW", added:
/* USER CODE BEGIN Includes */
#include "stdio.h"
/* USER CODE END Includes */
/* USER CODE BEGIN 0 */
int _write(int file, char *ptr, int len)
{
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
ITM_SendChar(*ptr++);
}
return len;
}
/* USER CODE END 0 */
and to the main loop
/* USER CODE BEGIN 2 */
int i = 0;
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
printf("%d Hello World!\n", ++i);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
Then I turn on SWV in the Debug Configuration and set the core clock to 170 Mhz. Lastly, I turn off the timestep in the SWV setting and enable port 0.
When I now run the project everything works and I get an output.
But when I then switch the project to C++ and rename the main.c to main.cpp. The project runs, but without any output.
| Because your _write function is not _write anymore as its name was mangled by the C++ compiler. So you link with the "old" one which does nothing You need to declare it a extern "C"
extern "C" {
void ITM_SendChar(char par);
int _write(int file, char *ptr, int len)
{
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
ITM_SendChar(*ptr++);
}
return len;
}
} /*extern "C"
|
69,808,960 | 69,808,961 | Get bash $PATH from C++ program | In the Terminal app my $PATH is:
/usr/local/opt/python/libexec/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin
If the user starts my C++ application using Dock, its $PATH is:
/usr/bin:/bin:/usr/sbin:/sbin
I would like my app to always has the same $PATH as terminal (bash) has.
Is there an easy way to achieve this?
The only way I'm aware of for now is to create a bash script on the disk with something like echo $PATH, launch it from my C++ program using bash -l command, read the output and update my process' PATH variable accordingly.
And, I do not want to change user system's config in any way. This should work without any additional actions required from the user and do not affect the user's system in any way.
| If you don’t like your solution of calling bash, here’s a stub to exercise more control over invoking shells and perhaps test if the user default shell isn’t bash all from within a c++ program:
setenv("PATH", "/MyCustomPath:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", 1);
To Read bash's path:
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (fgets(buffer, sizeof buffer, pipe) != NULL) {
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
setenv("PATH", exec("bash -l -c 'echo -n $PATH'").c_str(), 1);
|
69,809,252 | 69,810,095 | Locating a file by path/name in a zip using libarchive | I'm using libarchive in c/c++ to create a zip archive of files and I'm trying to find if there is a good way to find if a file name (or rather file in a path) already exists in a file.
Currently, my only way is to cycle through all the headers and compare the filenames to the one I am looking to put into the zip, based on the example code from the libarchive website:
struct mydata *mydata;
struct archive *a;
struct archive_entry *entry;
mydata = malloc(sizeof(struct mydata));
a = archive_read_new();
mydata->name = name;
mydata->fd = open(mydata->name, O_RDONLY); // Include O_BINARY on Windows
archive_read_support_compression_all(a);
archive_read_support_format_all(a);
archive_read_open(a, mydata, NULL, myread, myclose);
while (archive_read_next_header(a, &entry) == ARCHIVE_OK) {
printf("%s\n",archive_entry_pathname(entry));
}
archive_read_finish(a);
free(mydata);
The printf function has been edited in my code to a comparison. Obviously this has quite a significant overhead as the zip file gets bigger and there are a large number of headers to check.
Is this the best way or am I missing something simpler?
| As libarchive's README suggests, the library is intended for handling streaming archives, rather than randomly-accessed ones. It therefore stands to reason that, in order to locate a file in the archive, you have to "roll the tape", so to speak, until you reach it.
You could cache its contents in memory, like @kiner_shah suggests, by making a single pass over the archive with a while (archive_read_next_header(my_archive, &entry) == ARCHIVE_OK) { ... } loop; then you'll have whatever data structure you like for the different directories and files.
|
69,809,407 | 69,813,379 | How are variables related when using an allocator in C++? | I'm studying this piece of code and what I don't understand is how p, q and r are related. We assign p to q and p to r, then display r, even though we do the increment on q.
Then this do ... while loop:
do {
cout<< "here" << *r << endl;
} while (++r != q);
How does it work? What are r and q equal to?
This is the full code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
allocator<string> alloc;
auto const p = alloc.allocate(5);
auto q=p;
alloc.construct(q++);
alloc.construct(q++, 10, 'c');
alloc.construct(q++, "hi");
auto r=p;
do{
cout<< *r << endl;
}while (++r != q);
std::cout<<"done"<<endl;
while (q != p){
alloc.destroy(--q);
}
q=p; r=p;
alloc.construct(q++, 10, 'a');
alloc.construct(q++, "hi again");
do{
cout<< "here" << *r << endl;
}while (++r != q);
alloc.deallocate(p, 5);
}
The output is:
output:
cccccccccc
hi
done
hereaaaaaaaaaa
herehi again
| p is a std::string * const, aka "constant pointer to mutable string". q and r are initialised to copies of p, meaning they are std::string *, aka "mutable pointer to mutable string".
p always points to the first element of the allocated array. q and r are modified to point to other elements of the array.
The first block
auto q=p;
alloc.construct(q++);
alloc.construct(q++, 10, 'c');
alloc.construct(q++, "hi");
constructs 3 std::string objects, at consecutive positions in the array, starting with the first, incrementing q each time. q ends up pointing one-past the last std::string, to the forth element of the array.
The next block
auto r=p;
do{
cout<< *r << endl;
}while (++r != q);
displays these strings. After this, both q and r point to the forth element of the array.
The next block
while (q != p){
alloc.destroy(--q);
}
destroys each of those strings, in reverse order of construction. q ends up pointing to the first element, the same as p.
The first statement of the next block is a tautology, it sets q to the value it currently has, and then constructs 2 more strings. r is also reset to p.
q=p; r=p;
alloc.construct(q++, 10, 'a');
alloc.construct(q++, "hi again");
The next block displays those new strings, prepending "here".
do{
cout<< "here" << *r << endl;
}while (++r != q);
Finally the array is deallocated, without destroying the std::string objects. This might leak memory that the strings allocate, as their destructors are not run.
alloc.deallocate(p, 5);
|
69,810,225 | 69,810,294 | How to convert integer to string, preserving leading zeroes in C++ ? (Using to_string) | When I am trying to convert the given integer to string through to_string function, It simply omits the leading zeroes of the integer.
Why ? & how to overcome this?
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
string s = to_string(n);
cout << s;
}
| Integers doesn't have leading zeroes.
If you want a specific number of digits for the number, with leading zeros, you need to use I/O manipulators like set::setw and std::setfill:
std::cout << std::setw(8) << std::setfill('0') << n << '\n';
That will print (at least) eight digits, with leading zeros if the value of n is not eight digits.
If you want to store a "number" with leading zeros in your program, for example a phone number or similar, then you need another data-type than plain integers (which as mentioned doesn't have leading zeros).
Most common is as a string (std::string).
|
69,810,813 | 69,810,950 | Variadic templated type as return type, MSVC weirdness | Given the following code:
class DummyOK {
public:
template <typename U, typename... Args>
class AThing {
public:
};
public:
template <typename U, typename... Args>
AThing<U, Args...> GetAThing();
};
template <typename U, typename... Args>
typename DummyOK::template AThing<U, Args...> DummyOK::GetAThing() {
return AThing<U, Args...>{};
}
template <typename T>
class DummyKO {
public:
template <typename U, typename... Args>
class AThing {
public:
};
public:
template <typename U, typename... Args>
AThing<U, Args...> GetAThing();
template <typename U, typename... Args>
AThing<U, Args...> AnOtherGetAThing() {
return AThing<U, Args...>{};
}
};
template <typename T>
template <typename U, typename... Args>
typename DummyKO<T>::template AThing<U, Args...> DummyKO<T>::GetAThing() {
return AThing<U, Args...>{};
}
int main() {
DummyOK{}.GetAThing<char, unsigned, float>();
DummyKO<int>{}.GetAThing<char, unsigned, float>();
DummyKO<int>{}.AnOtherGetAThing<char, unsigned, float>();
return 0;
}
Also available here: https://godbolt.org/z/8747rj77K
Why does it compiles on clang/gcc but not msvc.
Why does AnOtherGetAThing() compiles but not GetAThing() (on msvc).
The error returned by msvc is:
<source>(39): error C2244: 'DummyKO<T>::GetAThing': unable to match function definition to an existing declaration
<source>(39): note: see declaration of 'DummyKO<T>::GetAThing'
<source>(39): note: definition
<source>(39): note: 'DummyKO<T>::AThing<U,Args...> DummyKO<T>::GetAThing(void)'
<source>(39): note: existing declarations
<source>(39): note: 'DummyKO<T>::AThing<U,Args...> DummyKO<T>::GetAThing(void)'
Thanks
| I would say msvc bug,
as workaround, you might use trailing return type:
template <typename T>
template <typename U, typename... Args>
auto DummyKO<T>::GetAThing() -> AThing<U, Args...>
{
// ...
}
Demo
|
69,811,461 | 72,196,373 | not recognized as a supported file format ECW gdal api | I'm trying to use ECW files in my application. I've built GDAL Library whit this command:
./configure --with-ecw:/usr/local/hexagon
after completion of build process, when I Entered:
gdalinfo --formats | grep ECW
I got:
ECW -raster- (rw+): ERDAS Compressed Wavelets (SDK 5.5)
JP2ECW -raster,vector- (rw+v): ERDAS JPEG2000 (SDK 5.5)
also when I've used
gdalinfo map.ecw
it returns all metadata of ECW files.
but when I compile my C++ program, it returns:
Error: GDAL Dataset returned null from read
ERROR 4: `map.ecw' not recognized as a supported file format.
Dose anyone know why I can't use ECW files in C++ program?
By the way, I use
Cmake
,GDAL 3.3.0
,Erdas-ECW SDK 5.5 hexagon
for building the program.
| I found the answer. This problem occurs if the gdal_bin binary package is installed before creating GDAL.
Just make sure gdal_bin is deleted before installing the version you created.
|
69,811,788 | 69,811,888 | Calculate total gross pay of 10 employees. (C++ - Array in Struct) | The result of this question, it should have a payroll record consists all of these things.
But i have a problem in calculating the TOTAL GROSS PAY FOR ALL EMPLOYEES by using arrays in struct (C++) but I am stuck.
The total gross pay should be printed at bottom of the payroll record. I feel like something is missing in my coding but I can`t figure out what that thing is. I only have a problem in finding the total gross pay, others are okay.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double gross[10];
double sum = 0.0;
double totalGrossPay;
struct GrossPay {
int empID;
string empName;
double chargeHour;
int workingHours;
double grossPay;
};
GrossPay employee[10];
for (int i = 0; i < 10; i++) {
cout << (i + 1) << "."
<< "Employee Name :";
cin >> employee[i].empName;
cout << "Employee ID :";
cin >> employee[i].empID;
cout << "Employee`s charge rate per hour :";
cin >> employee[i].chargeHour;
cout << "Working hours :";
cin >> employee[i].workingHours;
cout << endl;
}
cout << "Employee ID\t"
<< "Employee Name\t"
<< "Gross Pay(RM)" << endl;
for (int i = 0; i < 10; i++) {
double gross = employee[i].chargeHour * employee[i].workingHours;
cout << employee[i].empID << "\t\t" << employee[i].empName << "\t\t" << gross;
cout << endl;
}
cout << endl;
for (int i = 0; i < 10; i++) {
totalGrossPay = sum + gross[i];
}
cout << "Total gross pay of 10 employees : RM" << totalGrossPay;
return 0;
}
| You have an uninitialized array
double gross[10];
So its elements have indeterminate values.
As a result this loop
for (int i = 0; i < 10; i++) {
totalGrossPay = sum + gross[i];
}
invokes undefined behavior.
Also the variable sum has not changed in the preceding code. So its using in this for loop does not make a sense.
Maybe you mean in the body of the loop
double totalGrossPay = 0.0;
for (int i = 0; i < 10; i++) {
totalGrossPay += gross[i];
}
provided that the array gross is filled with values.
It seems that in this for loop
for (int i = 0; i < 10; i++) {
double gross = employee[i].chargeHour * employee[i].workingHours;
cout << employee[i].empID << "\t\t" << employee[i].empName << "\t\t" << gross;
cout << endl;
}
you mean elements of the array gross instead of the local variable gross as for example
for (int i = 0; i < 10; i++) {
gross[i] = employee[i].chargeHour * employee[i].workingHours;
cout << employee[i].empID << "\t\t" << employee[i].empName << "\t\t" << gross[i];
cout << endl;
}
Also the data member double grossPay; of the structure is not used. Maybe instead of the array gross you need to fill this data member of elements of the array of structures do not you?
|
69,811,934 | 69,812,485 | Would it be possible to call a function in every instance of a class in C++ | #include <iostream>
#include <string>
class Game {
public:
virtual void Tick() {
// Somehow call the tick in every instance of "Object" or any derived class
}
};
class Object : public Game {
public:
std::string Name;
Object(std::string name) : Name(_name){
}
void Tick(){
// Do something every update
std::cout << this->Name << std::endl;
}
};
int main() {
Game* game = new Game();
Object* obj1 = new Object(), *obj2 = new Object();
while (1) {
// A game loop that will call all the classes
game->Tick();
}
}
Would it be possible to call a function in the "Game" class that calls it in every instance of the "Object" class?
Like Game->Tick() which would call the tick function in obj1 and obj2
I have made one previously where all of the objects were stored in an std::vector but I felt this was too slow and I was wondering if this way was possible, should I stick to the array method of updating each object?
I am just curios as I would like to make a simple game just to try it out
| Yes it is possible, but you probably do not want that.
First, you are using inheritance between Game and Object. Inheritance is a is a relation. Are your really sure that all Object instances are also Game instances?
If you want to call a method on a bunch of instance, then you need a container for those instances and you will iterate on it. If you really want the container to know all instances, you could make it a static member or the class, have the constructor to add a pointer to the object to the container and the destructor to remove it. Without more details I would use a std::set<Object *> here because insertion and removal are simple.
But care must be taken to add a custom copy constructor, because the default copy constructor would not add a newly created object to the container (thanks to @Caleth for pointing it out)
Here is the modified code:
#include <iostream>
#include <string>
#include <set>
// An abstract class for classes having a Tick() metho
class Tickable {
public:
virtual void Tick() = 0;
virtual ~Tickable() {}
};
class Game: public Tickable {
public:
virtual void Tick(); // definition will follow Object definition
};
class Object : public Tickable {
static std::set<Object*> instances; // THE container
public:
std::string Name;
Object(std::string name="") : Name(name) {
instances.insert(this); // add here
}
// do not forget a custom copy ctor...
Object(const Object& other) : Name(other.Name) {
instances.insert(this);
}
void Tick() {
// Do something every update
std::cout << this->Name << std::endl;
}
~Object() {
instances.erase(this); //and remove there
}
// only publicly give a const reference to the internal container
static const std::set<Object*>& getInstances() {
return instances;
}
};
void Game::Tick() {
// Somehow call the tick in every instance of "Object" or any derived class
for (Object* obj : Object::getInstances()) {
obj->Tick();
}
}
std::set<Object*> Object::instances; // required per One Definition Rule...
int main() {
Game* game = new Game();
Object* obj1 = new Object("foo"), * obj2 = new Object("bar");
// A game loop that will call all the classes
game->Tick();
}
It will give as expected:
foo
bar
|
69,812,337 | 69,812,467 | Accessing private member from derived class | This might be a trivial question. Have below code,
class message {
public:
virtual void setMessage(const string& name, const int& age, const string& title) const;
virtual void getMessage(const string& name) const;
private:
void removeMessage(const string& name);
};
class test : public message {
public:
using message::removeMessage;
};
int main()
{
test t;
t.removeMessage("_");
while (1);
return 0;
}
Trying to expose removeMessage() as a public method from the test class. But this is giving error that,
error C2876: 'message': not all overloads are accessible
How to expose a private method in base class as public in derived class?
| Private members can never be accessed on derived classes. If your intention is to have the derived class access the members of the base class then make those protected or public.
|
69,812,896 | 69,812,937 | Why is this working in a normal for loop but not a range based for loop? | void set_fee(Patron p, int fee)
{
for (Patron x : patrons)
{
if (p.get_name() == x.get_name()) x.set_fee(fee);
}
for (int i = 0; i < patrons.size(); i++)
{
if (patrons[i].get_name() == p.get_name()) patrons[i].set_fee(fee);
}
}
So patron is just some class I made and none of the functions here really matter get_name() just returns the object's name and set_fee(fee) just sets the fee of the object to fee.
But does anyone have any idea for why the first loop doesn't work but the second one does? I basically just wanna look for p inside the patrons vector and once I find it I want to change the fee of the patron object inside the vector, but the first way doesn't work, why?
| Your x in the range based for loop is a copy of the element in the vector. You need to have reference there
for (Patron& x : patrons)
// ^^^^^^^^
{
// ....
}
or else x.set_fee(fee); will be called on the copy.
|
69,814,275 | 69,819,146 | Why aren't my Microsoft Visual Studio 2017 debugging toolbar commands showing? |
I can't see neither my breakpoints or any debugging commands. I have installed Microsoft Visual Studio 2017 and I'm currently editing a c++ source file and i'm having big troubles with debugging. Does anyone know a fix?
| Reinstall VS should be the last resort, you can try below suggestions first.
Please try to restart VS 2017 and if it doesn’t work, try to reboot your machine.
Please try to repair Visual Studio like Alan mentioned, in Visual Studio Installer > find Visual Studio 2017 > More > Repair.
Make sure that you are not using some extensions which may cause incompatibility. If you installed some extensions, please try to disable them temporary(Tools > Extensions and Updates… > find the extension you installed manually before > select it > Disable) and restart VS 2017.
Also, please try to delete the hidden .vs folder in your solution folder, and then try to start debugging again.
Sometimes, updating VS 2017(VS Installer > find VS 2017 > Update) will work.
|
69,814,356 | 69,814,606 | std::move on const char* with perfect forwarding | I have an interesting issue on the MSVC v19.28 compiler (later versions fix this problem) where a const char* being passed to a variadic template class fails to resolve correctly. If the const char* is passed to a variadic template function then there are no errors.
Here's the code for clarity:
#include <type_traits>
template <typename... T_Args>
struct Foo
{
template <typename T_Func>
void foo(T_Func func, T_Args&&... args)
{
func(std::forward<T_Args>(args)...);
}
};
template <typename T_Func, typename... T_Args>
void bar(T_Func func, T_Args&&... args)
{
func(std::forward<T_Args>(args)...);
}
int main()
{
bar([](int, float, const char* c){ }, 5, 5.0f, "Hello world");
// <source>(26): error C2672: 'Foo<int,float,const char *>::foo': no matching overloaded function found
// <source>(26): error C2440: 'initializing': cannot convert from 'const char [12]' to 'const char *&&'
// <source>(26): note: You cannot bind an lvalue to an rvalue reference
Foo<int, float, const char*> f;
f.foo([](int, float, const char* c){ }, 5, 5.0f, "Hello world");
// this compiles, but what are the repurcussions of std::move() on a string literal?
Foo<int, float, const char*> g;
g.foo([](int, float, const char* c){ }, 5, 5.0f, std::move("Hello world"));
}
Since I work on a large team, I am unable to recommend upgrading the toolchain/compiler and so I am looking for workarounds until the compiler can be updated.
One of the workaround is to use std::move("Hello world"). What is std::move doing do a const char* and what the potential side-effects?
|
What is std::move doing to a const char [12] and what are the potential side-effects?
The ordinary array-to-pointer implicit conversion, and none. Pointer types don't have move constructors or move assignment operators, so "moves" are copies (of the pointer the array decayed to).
Aside: I don't think your template does what you think it does. The pack T_Args... isn't deduced in when calling Foo::foo, so you don't have a universal reference, instead it's rvalue references.
Did you mean something like
template <typename... T_Args>
struct Foo
{
template <typename T_Func, typename... T_Args2>
void foo(T_Func func, T_Args2&&... args)
{
static_assert(std::is_constructible_v<T_Args, T_Args2> && ..., "Arguments must match parameters");
func(std::forward<T_Args2>(args)...);
}
};
Or possibly the even simpler
struct Foo
{
template <typename T_Func, typename... T_Args>
void foo(T_Func func, T_Args&&... args)
{
func(std::forward<T_Args>(args)...);
}
};
|
69,814,384 | 69,814,494 | How to read memcpy struct result via a pointer | I want to copy a struct content in memory via char* pc the print it back but here I have an exception (reading violation)
struct af {
bool a;
uint8_t b;
uint16_t c;
};
int main() {
af t;
t.a = true;
t.b = 3;
t.c = 20;
char* pc = nullptr;
memcpy(&pc, &t, sizeof(t));
std::cout << "msg is " << pc << std::endl; // here the exception
return 0;
}
then I want to recover data from memory to another structure of same type.
I did af* tt = (af*)(pc); then tried to access to tt->a but always an exception.
| You need to allocate memory before you can copy something into it. Also, pc is already the pointer, you need not take the address of it again. Moreover, the byte representation is very likely to contain non-printable characters. To see the actual effect the following copies from the buffer back to an af and prints its members (note that a cast is needed to prevent std::cout to interpret the uint8_t as a character):
#include <iostream>
#include <cstring>
struct af {
bool a;
uint8_t b;
uint16_t c;
};
int main() {
af t;
t.a = true;
t.b = 3;
t.c = 20;
char pc[sizeof(af)];
std::memcpy(pc, &t, sizeof(t)); // array pc decays to pointer to first element
for (int i=0;i<sizeof(af); ++i){
std::cout << i << " " << pc[i] << "\n";
}
af t2;
std::memcpy(&t2, pc,sizeof(t));
std::cout << t2.a << " " << static_cast<unsigned>(t2.b) << " " << t2.c;
}
Output:
0
1
2
3
1 3 20
Note that I replaced the output of pc with a loop that prints individual characters, because the binary representation might contain null terminators and pc is not a null terminated string. If you want it to be a null-terminated string, it must be of size sizeof(af) +1 and have a terminating '\0'.
|
69,814,585 | 69,826,545 | C++ iterator argument in abstract class | I want to have an abstract class with a read and write method like:
template<typename Iterator>
virtual void read(uint64_t adr, Iterator begin, Iterator end) const = 0;
template<typename Iterator>
virtual void write(uint64_t adr, Iterator begin, Iterator end) const = 0;
is there a way to achieve something like that?
Since there can't be a virtual template method, I thought about
Get rid of the abstract class and use a template instead.
In the template I would assume there is a read/write method taking an iterator.
Make the abstract class a template too and pass the iterator type.
Is one of these ways a clean one?
I'm on C++11 btw
|
Is one of these ways a clean one?
Yes: use static polymorphism instead of virtual functions. When a type is passed via a template, it is not erased and therefore needs no pre-generated virtual tables, so you can cause further template instantiation - that's what your use-case begs for.
Solution 1 (recommended)
So, if your abstract class is used as just an "interface", get rid of it and write read/write in the "implementations" directly:
struct Impl {
template<typename Iterator> void read(uint64_t, Iterator, Iterator) const { /* work */ }
template<typename Iterator> void write(uint64_t, Iterator, Iterator) const { /* work */ }
};
and replace usages of your implementation classes through that abstract class with
template<typename Impl> void use_any_impl(Impl&&) { /* work */ }
However, if your abstract class contains some logic/data which is meant to be inherited, you can keep the class but get rid of anything virtual:
class Abstract {
protected: ~Abstract() = default;
public: constexpr int inherit_me() const { return 42; }
};
class Impl: public Abstract { /* read() and write() same as above */ };
/* use_any_impl() same as above */
Solution 2
If your templated Iterators always (or can be reduced to) lead to a raw array storage (e.g. one provided by std::vector<unsigned char>::data), which seems reasonable for raw read/write operations, you can just use raw pointers:
virtual void read(uint64_t, unsigned char*, unsigned char*) const = 0;
virtual void write(uint64_t, unsigned char*, unsigned char*) const = 0;
|
69,814,706 | 69,815,009 | __declspec(dllexport) on nested classes | Code:
#ifdef BUILD_DLL
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif
class MY_API A
{
public:
void some_method();
class B
{
public:
void other_method();
};
};
Do I have to add my macro (MY_API) to the B class?
|
Do I have to add my macro (MY_API) to the B class?
If that B class is also exported/imported (which, presumably, it is), then: Yes, you do.
Try the following code, where we are building the DLL and exporting the classes:
#define BUILD_DLL
#ifdef BUILD_DLL
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif
class MY_API A {
public:
void some_method();
class B {
public:
void other_method();
};
};
// Dummy definitions of the exported member functions:
void MY_API A::some_method() {}
void MY_API A::B::other_method() {}
Compiling this gives the following error (MSVC, Visual Studio 2019):
error C2375: 'A::B::other_method': redefinition; different linkage
The message disappears, and the code compiles without issue, if we simply add the MY_APP attribute to the nested class:
//...
class MY_API B { // Add attribute to nested class
//...
|
69,815,016 | 69,815,087 | I need to print static matrix overloading "<<" operator | I need to print static matrix overloading "<<" operator. Here is my code:
class Matrix
{
public:
int matrix[3][3];
friend std::ostream& operator<<(std::ostream& out, const Matrix& e);
};
std::ostream& operator<<(std::ostream& out, const Matrix& e)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
out << e.matrix[i][j]<<" ";
}
out << std::endl;
}
out << std::endl;
return out;
}
and main function
int main
{
int A[3][3] = { {1,1,1},{1,0,0},{0,0,1} };
}
My problem is I don't know how to use in main function my overloaded operator to print matrix A.
|
I don't know how to use in main function my overloaded operator to print matrix A
First, you need to create an instance of your Matrix class, then you can print it:
int main()
{
Matrix A = {{{1,1,1}, {1,0,0}, {0,0,1}}};
std::cout << A;
}
Side note: I suggest replacing all out << std::endl; with out << '\n'; in your operator<<. You should let the user std::flush if the user actually needs it.
|
69,815,497 | 69,815,582 | int count{0}. Can I initialize a variable using curly braces in C++? | I am in first year in BSc Computer Science. I received a comment from my Professor on my recently submitted assignment . I initialized an int variable to zero : int count{0};. The book assigned to us in the course gives only one way to initialize a variable by using an assignment statement.
int count = 0;
I don't remember where I learnt the curly braces method to initialize the variable. According to my professor , this is not a legal way to do it. My program runs without any errors in Atom and also on online debugger. I always check my program for errors from two different platforms. So, I am confused whether my method was wrong and was missed by the compiler or this method is legal but not considered standard.
Any clarification will be helpful. Also any advice on good programming practices for debugging, so it doesn't happen again as I lost 4 marks from a 10 mark assignment.
| Here is how you may initialize the variable count of the type int with zero
int count = 0;
int count = { 0 };
int count = ( 0 );
int count{ 0 };
int count( 0 );
int count = {};
int count{};
You may not write
int count();
because this will be a function declaration.
If to use the specifier auto then these declarations
auto count = { 0 };
auto count = {};
must be excluded from the above list because in this case in the first declaration the variable count will have the type std::initializer_list<int> and in the second declaration the type of the variable can not be deduced.
Pay attention to that the initialization of scalar objects with a braced list was introduced in C++ 11.
|
69,815,597 | 69,815,862 | How to shuffle an array in C++? | I have an array:
names[4]={john,david,jack,harry};
and i want to do it randomly shuffle, like:
names[4]={jack,david,john,harry};
I tried to use this but it just shuffled the letters of the first word in the array:
random_shuffle(names->begin(), names->end());
Here is the full code, it reads names from a .txt file and puts in an array:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
ifstream readName("names.txt");
string names[197];
int i = 0;
for (string line; getline(readName, line); ){
readName >> names[i];
i++;
}
readName.close();
random_shuffle(names->begin(), names->end());
for (int i = 0; i < 197; i++) {
cout << names[i] << endl;
}
return 0;
}
I tried few other things from different people but I couldn't manage to work it.. Anything helps, thank you!
| Here's your code with what I felt were the smallest amount of changes. One could argue that I didn't need to change your first for loop as much, but I figure that if you have the prescience to know how many names you're reading, you might as well use the knowledge.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator> // std::begin(), std::end(); required for C-arrays
#include <random> // std::mt19937; needed to feed std::shuffle()
#include <string>
// using namespace std; // BAD PRACTICE
int main() {
constexpr int size = 4; // Give your magic number a name; only need to change
// a single location
std::ifstream readName("names.txt");
if (!readName) { // Always check that you successfully opened the file.
std::cerr << "Error opening file.\n";
return 1;
}
std::string names[size];
// int i = 0;
for (int i = 0; i < size; ++i) { // Retool the loop entirely
std::getline(readName, names[i]);
}
readName.close();
// This is a fragile solution. It's only working because the array is in
// scope
std::shuffle(std::begin(names), std::end(names),
std::mt19937{std::random_device{}()});
for (int i = 0; i < size; i++) {
std::cout << names[i]
<< '\n'; // Don't use std::endl unless you actually need it
}
return 0;
}
This is not ideal code, though. Any change to the size of the input file requires changing the code and re-compiling. The biggest single change was to get rid of std::random_shuffle and use std::shuffle() instead. std::random_shuffle was deprecated with C++14 and removed in C++17. It's bad to use it. std::shuffle() does add the requirement of providing a PRNG, but it's not so bad. It leads to better code if you have a PRNG that needs to randomize many different things in a bigger program. This is because it's good to have a single PRNG and let it live for the length of your program as opposed to constantly building new ones.
And the C-array just makes things a bit clunkier. Enter std::vector.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <random> // std::mt19937; needed to feed std::shuffle()
#include <string>
#include <vector>
int main() {
std::ifstream readName("names.txt");
if (!readName) { // Always check that you successfully opened the file.
std::cerr << "Error opening file.\n";
return 1;
}
std::vector<std::string> names;
std::string name;
while (std::getline(readName, name)) { // Retool the loop entirely
names.push_back(name);
}
readName.close();
std::shuffle(std::begin(names), std::end(names),
std::mt19937{std::random_device{}()});
for (const auto& i : names) {
std::cout << i << '\n';
}
return 0;
}
The vector can grow as needed, so you see how much simpler the loop that reads the names becomes. It's also more flexible since you don't have to know ahead of time how many entries to expect. It will "just work." With the call to std::shuffle() I kept the std::begin(names) syntax because many consider this a best practice, but you could have also used names.begin() if you wanted since the vector class provides its own iterators.
|
69,815,719 | 69,818,455 | Eigen::VectorXd constructor desires MatrixXd when compiling | Have a straightforward problem with testing out some Eigen functionality. I'm creating a constructor that takes 3 Eigen::Vector by reference. When I construct those 3 in my main and call the Interp object (the class I created) constructor, I get that the constructor desires Eigen::MatrixXd (see the compile error at the bottom of this question). My code is shown below. I haven't added much functionality yet so I'd say it's a pretty bare-bone problem but I can't find a solution myself.
main.cpp
#include "Interp.hpp"
int main(){
Eigen::VectorXd xData(4);
xData << 0.0, 0.33, 0.66, 1.00;
Eigen::VectorXd zData(4);
zData << 0.0, 1.0, 0.5, 0.0;
Eigen::VectorXd dzData(4);
dzData << 0.0, 0.0, 0.0, 0.0;
Interp obj(xData,zData,dzData);
}
Interp.hpp
#include <iostream>
#include <vector>
#include <eigen3/Eigen/Dense>
class Interp {
public:
Interp(Eigen::VectorXd &xData, Eigen::VectorXd &zData, Eigen::VectorXd &dzData);
void compute();
double evaluate(double &x);
Eigen::VectorXd evaluate(Eigen::VectorXd &x);
private:
Eigen::VectorXd xData;
Eigen::VectorXd zData;
Eigen::VectorXd dzData;
Eigen::MatrixXd xPoints;
Eigen::VectorXd p;
Eigen::MatrixXd A;
Eigen::MatrixXd b;
};
Interp.cpp
#include "Interp.hpp"
Interp::Interp(Eigen::VectorXd &xData, Eigen::VectorXd &zData, Eigen::VectorXd &dzData){
this->xData = xData;
this->zData = zData;
this->dzData = dzData;
this->xPoints.resize(xData.size()-1,2);
}
And I build using CMake, so my CMakeLists.txt file is:
CmakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(test1 VERSION 0.1.0)
include(CTest)
enable_testing()
find_package (Eigen3 3.3 REQUIRED NO_MODULE)
add_executable(test1 main.cpp)
target_link_libraries (test1 Eigen3::Eigen)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
The output I get is as follows:
[main] Building folder: test
[build] Starting build
[proc] Executing command: /usr/bin/cmake --build /home/none/test/build --config Debug --target all -- -j 10
[build] Scanning dependencies of target test1
[build] [ 50%] Building CXX object CMakeFiles/test1.dir/main.cpp.o
[build] [100%] Linking CXX executable test1
[build] CMakeFiles/test1.dir/main.cpp.o: In function `main':
[build] /home/none/test/main.cpp:11: undefined reference to `Interp::Interp(Eigen::Matrix<double, -1, 1, 0, -1, 1>&, Eigen::Matrix<double, -1, 1, 0, -1, 1>&, Eigen::Matrix<double, -1, 1, 0, -1, 1>&)'
[build] collect2: error: ld returned 1 exit status
[build] CMakeFiles/test1.dir/build.make:94: recipe for target 'test1' failed
[build] make[2]: *** [test1] Error 1
[build] make[1]: *** [CMakeFiles/test1.dir/all] Error 2
[build] CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/test1.dir/all' failed
[build] Makefile:116: recipe for target 'all' failed
[build] make: *** [all] Error 2
[build] Build finished with exit code 2
Where roughly in the middle you would see that there is an undefined reference to a Matrix constructor. I understand that a VectorXd is an inherited type of a Matrix but I did not expect that this would give me any trouble when calling the constructor. It is still its own type after all.
So quite a straightforward problem but I'm at a loss on what to do. Any help would be appreciated.
| For the answer, please see @rafix07 in the comments below my initial question:
"You are not compiling
Interp.cpp
try
add_executable(test1 main.cpp interp.cpp)"
-- rafix07
|
69,816,039 | 69,816,135 | Constructor with multiple parameters throws 'expression list treated as compound expression in initializer' when array of classes declared | I created the following test program to demonstrate an error I can't seem to resolve. I have searched and read several articles, but none that I've found explain how to resolve this particular problem.
I created a class with multiple constructors, one of which has multiple parameters. I can declare instances of the class testing each constructor, but when I declare an array of classes I can only use the default constructor or the version with a single parameter.
I get a compile error: "expression list treated as compound expression in initializer [-fpermissive]" when I create an array of classes and attempt to use the multiparameter constructor. I am using C++11 mingw compiler, see kc5 in the below sample program.
Can anyone explain the meaning of the error and how to properly declare an array of class objects when the constructor has multiple parameters?
#include <iostream>
using namespace std;
class KClass {
public:
int x=0;
KClass(){};//default constructor w/o parameters works
KClass(int a){//single parameter constructor works
x = a;
return;
}
KClass(char c,int a){//multi parameter constructor
x = a;
//not using char c for now
return;
}
~KClass(){};//destructor
int getx(){return x;}
void setx(int data){x=data;return;}
};
//class is declared, let's create some instances of the class
KClass kc0;//works
KClass kc1(5);//works
KClass kc2('k',7);//works
KClass kc3[2];//works
KClass kc4[2](4);//works
//next line does not compile (how do I fix?)
KClass kc5[2]('r',4);//compile error: expression list treated as compound expression in initializer
int main()
{
//do something
getchar();
return 0;
}
I learned that using the 'new' keyword works, however, the solution doesn't seem elegant to me and I don't understand why 'new' is required.
KClass *kc6 = new KClass[2]; //works
and then in main() I initialize using the multiparameter constructor.
kc6[0] = KClass('a',2);
kc6[1] = KClass('b',3);
| Such an initialization of an array
KClass kc5[2]('r',4);
is allowed by the C++ 20 Standard. In this case the constructor with one parameter will be called for each element.
If the compiler does not support the C++ 20 Standard then it will issue an error.
Otherwise in C++ 20 you could else write
KClass kc5[2]( { 'r',4 } );
and for the first element the constructor with two parameters will be called.
|
69,816,126 | 69,816,748 | c++ nested while loop runs only once | Please can you advise, why the inner loop runs only once?
I'd like to add suffix to each line of input file and then store the result in output file.
thanks
For example:
Input file contains:
AA
AB
AC
Suffix file contains:
_1
_2
Output file should contain:
AA_1
AB_1
AC_1
AA_2
AB_2
AC_2
My result is :
AA_1
AB_1
AC_1
Code:
int main()
{
string line_in{};
string line_suf{};
string line_out{};
ifstream inFile{};
ofstream outFile{"outfile.txt"};
ifstream suffix{};
inFile.open("combined_test.txt");
suffix.open("suffixes.txt");
if (!inFile.is_open() && !suffix.is_open()) {
perror("Error open");
exit(EXIT_FAILURE);
}
while (getline(suffix, line_suf)) {
while (getline(inFile, line_in))
{
line_out = line_in + line_suf;
outFile << line_out << endl;
}
inFile.close();
outFile.close();
}
}
| IMHO, a better method is to read the files into vectors, then iterate through the vectors:
std::ifstream word_base_file("combined_test.txt");
std::ifstream suffix_file("suffixes.txt");
//...
std::vector<string> words;
std::vector<string> suffixes;
std::string text;
while (std::getline(word_base_file, text))
{
words.push_back(text);
}
while (std::getline(suffix_file, text))
{
suffixes.push_back(text);
}
//...
const unsigned int quantity_words(words.size());
const unsigned int quantity_suffixes(suffixes.size());
for (unsigned int i = 0u; i < quantity_words; ++i)
{
for (unsigned int j = 0; j < quantity_suffixes; ++j)
{
std::cout << words[i] << suffix[j] << "\n";
}
}
Edit 1: no vectors
If you haven't learned about vectors or like to thrash your storage device you could try this:
std::string word_base;
while (std::getline(inFile, word_base))
{
std::string suffix_text;
while (std::getline(suffixes, suffix_text))
{
std::cout << word_base << suffix_text << "\n";
}
suffixes.clear(); // Clear the EOF condition
suffixes.seekg(0); // Seek to the start of the file (rewind).
}
Remember, after the inner while loop, the suffixes file is at the end; no more reads can occur. Thus the file needs to be positioned at the start before reading. Also, the EOF state needs to be cleared before reading.
|
69,816,140 | 69,816,514 | How to keep count of right answer and wrong answers in C++? | Currently working on addition program that will loop until the user enters "n".
It will generate two random numbers and display to the user to add them. The user will then input the answer and the program with check if the answer is right or wrong.
My code is working fine however I need help for my code below to keep count of right and wrong answers.
I have not tired anything because I do not know how to do it.
/******************************************************************************
Basic Template for our C++ Programs.
STRING
*******************************************************************************/
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string> // String managment funtions.
#include <iostream> // For input and output
#include <cmath> // For math functions.
#include <math.h>
#include <cstdlib>
using namespace std;
////////////////////////////////////////////////////////////////////////
int main()
{
srand(time(0));
string keepgoing;
do
{
const int minValue = 10;
const int maxValue = 20;
int y = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is x "<< x << endl;
cout << " what is the sum of " << x << " + " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x + y))
{
cout << "Great!! You are really smart!!" << endl;
}
else
{
cout << "You need to review your basic concepts of addition" << endl;
}
cout << "Do you want to try agian [enter y (yes) or n (no) ]";
cin >> keepgoing;
} while (keepgoing == "y");
return 0;
}
| To make life easier, let's use two variables:
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
(This should go before the do statement.)
When you detect a correct answer then increment one of these variables:
if (answer = (x+y))
{
++quantity_correct_answers;
}
else
{
++quantity_wrong_answers;
}
Before returning from main, you could print the statistics.
|
69,816,274 | 69,817,853 | Is there a Python fstring or string formatting equivalent in C++? | I'm working on a project in C++ and I needed to make a string that has elements of an array in it. I know in python you have things like sting formatting and fstrings, but I don't know if C++ has any equivalent. I have no earthly idea as to whether or not that's a thing, so I figured this is the best place to ask. I'm making a tic-tac-toe game and I have the board made and I have the positions on the board made. All I'm trying to do is optimize the board so that I can call it from one function in another function and have the parent function return the board so I can work with it. My basic idea for how to do this was to take the board and turn it all into one big string with a bunch of newlines in it and the array elements in it. I also made it in a function so I can just call it wherever I need it and just have it there. Here is the board function I made:
void board(){
char board_pos[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
cout << " | | " << endl;
cout << " " << board_pos[0][0] << " | " << board_pos[0][1] << " | " << board_pos[0][2] << " " << endl;
cout << " | | " << endl;
cout << "-----------------" << endl;
cout << " | | " << endl;
cout << " " << board_pos[1][0] << " | " << board_pos[1][1] << " | " << board_pos[1][2] << " " << endl;
cout << " | | " << endl;
cout << "-----------------" << endl;
cout << " | | " << endl;
cout << " " << board_pos[2][0] << " | " << board_pos[2][1] << " | " << board_pos[2][2] << " " << endl;
cout << " | | " << endl;
}
Edit: I got it figured out thanks to the help of you guys, I really appreciate it. :)
| I would just return the type that you use to hold the board. In your case you started with char[3][3].
I would write that using the C++11 array:
using Row = std::array<char, 3>;
using Board = std::array<Row, 3>;
Now you can make all kinds of functions:
void move(char player, Board const& b, int row, int col);
bool is_game_over(Board const&);
void print(Board const& b);
Etc.
Your print function could be:
void print(Board const& b)
{
std::cout << " | | \n";
auto print_row = [](Row const& row) {
std::cout << " " << row[0] << " | " << row[1] << " | " << row[2]
<< " \n";
};
print_row(b[0]);
std::cout << " | | \n";
std::cout << "-----------------\n";
std::cout << " | | \n";
print_row(b[1]);
std::cout << " | | \n";
std::cout << "-----------------\n";
std::cout << " | | \n";
print_row(b[2]);
std::cout << " | | \n";
}
See it Live
Prints
| |
1 | 2 | 3
| |
-----------------
| |
4 | 5 | 6
| |
-----------------
| |
7 | 8 | 9
| |
|
69,816,400 | 69,816,432 | Segmentation fault (core dumped) - Use of uninitialised value of size 8 | #include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class Node{
private:
Node *parent;
string name;
public:
Node(){
}
Node(string nodeName, Node *nodeParent){
setName(nodeName);
setParent(nodeParent);
}
Node getParent(){
return *parent;
}
void setParent(Node *p){
parent = p;
}
string getName(){
return name;
}
void setName(string n){
name = n; //<--this is where the code fails...
}
};
class Child1 : public Node {
};
class Child2 : public Node {
};
class Graph {
private:
string name;
Node root;
void setName(string n){ name = n; }
void setRoot(Node r){ root = r; }
public:
Graph(string n, Node r){ //Constructor
setName(n);
setRoot(r);
Node *root = new Node();
string name = "Root";
root->setName(name);
Node *node1 = new Node("Node1", root);
Node *node2 = new Node("Node2", root);
Node *node3 = new Node("Node3", node2);
Child1 *child1;
child1->setName("Child1");
child1->setParent(root);
Child2 *child2;
child2->setName("Child2");
child2->setParent(node1);
}
string getName(){
return name;
}
Node getRoot(){
return root;
}
};
int main() {
Node *root = new Node();
root->setName("Root");
Graph *sg = new Graph("Graph", *root);
};
Hello everyone. I am trying to build a node structure. But, as you can see, I am not very good at c++. I am getting Segmentation fault (core dumped) error in Visual Studio Code. So also tried in https://pythontutor.com/ and it gave me ERROR: Use of uninitialised value of size 8. I could not find where to initialize name. Can you help me?
Also the code is not efficient. I had to define two separate root: one in main() and one in Graph Constructor because could not figure out how to use pointers. If you can explain a way to make it more efficient, it would be great. But it is not that necessary right now.
EDIT
I created constructures for Child1 and Child2.
Then change:
Child1 *child1; to Child1 *child1 = new Child1();
Child2 *child2; to Child2 *child2 = new Child2();
The error is gone.
| Child1 *child1;
child1->setName("Child1");
child1->setParent(root);
Child2 *child2;
child2->setName("Child2");
child2->setParent(node1);
With both of these, you're taking an uninitialized pointer (child1 and child2) and trying to dereference it.
You probably want something on this order:
Child1 *child1 = new Child1;
child1->setName("Child1");
// ...
Child2 *child2 = new Child2;
// ...
It's going to take a bit more than that to actually create a graph, but this will at least fix the error message you're seeing. To do something very meaningful, you're going to want each node to container at least one (and probably an arbitrary number of) pointers to child nodes. Then you'll want the root's child pointer to point to child1, and child1's child pointer to point to child2 (or something on that order).
|
69,816,670 | 69,817,473 | Cmake Commandline parameters only - Linking external library using | I am new to Cmake and learning. I am using Ubuntu 20
I am not allowed to make changes CMakeLists.txt file. I am trying to use -DIMPORTED_LOCATION=/home/map/third_party for linking external library(libdlt.so) which is present in a user-defined location instead of the default location. But with this command, I am getting the following error
/usr/bin/ld: cannot find -ldlt
collect2: error: ld returned 1 exit status
Could you please help to clarify why it is not picking this parameter? If this library(libdlt.so) is at default location(/etc/local/lib) then CMake is working correctly.
Thanks
<
| You can't do this only with command line parameters.
The IMPORTED_LOCATION is a target property. This means it only has meaning to CMake when applying it to a CMake target.
Dependencies in CMake usually are managed with imported targets, which has the IMPORTED_LOCATION property.
It would be done like this:
find_path(DLT_INCLUDE_DIRECTORY dlt/dlt.h)
find_library(DLT_LIBRARY NAMES dlt)
add_library(dlt::dlt IMPORTED)
set_target_properties(dlt::dlt PROPERTIES
IMPORTED_LOCATION ${DLT_LIBRARY}
INTERFACE_INCLUDE_DIRECTORIES ${DLT_INCLUDE_DIRECTORY}
)
# then, later in your CMake scripts...
target_link_libraries(yourExecutable PUBLIC dlt::dlt)
You first find the paths. Include directory and library path.
Then, you create an imported target and set the path as its properties.
Then call CMake with the right prefix path so the find_* command search in the right directory:
cmake .. -DCMAKE_PREFIX_PATH=/home/map/third_party
Now as you mentionned in the comments, you cannot change the CMakeLists file.
If you're using a library that has this broken CMake script, I would suggest forking it and fix their CMake file to not be hardcoded.
If you insist on not modifying the CMake file, there's a couple of things you can do.
You can create your own CMakeLists.txt, and use it instead. Yes you can do that! It is hackish but allows you to have a modifiable CMakeLists.txt that you can fix its behavior.
Create a sibling directory to the unmodifiable project, and add a CMakeLists.txt in it and a build/ directory.
In those CMake, use relative paths like this:
add_library(yourlib STATIC)
target_sources(yourlib ../yourproject/file1.cpp ../yourproject/file2.cpp)
Then, use proper find_XXX function so CMake can have a chance to find the right library instead of an hardcoded path.
There's another hack, but it's a bit more hackish.
You can replace the link program that CMake uses with a custom one with a command line argument:
cmake .. -DCMAKE_LINKER=/path/to/linker -DCMAKE_CXX_LINK_EXECUTABLE="<CMAKE_LINKER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>"
You can replace /path/to/linker with a script that will replace the hardcoded flags with the good ones instead.
This is very hackish. Expect things to break or not behave correctly.
If you cannot create a separated CMakeLists script and replacing the link program is not an option either, there's another hack you can do. This is incredibly hackish, hard to create, hard to maintain, beginner unfriendly solution, and also very brittle and can break easily.
I must warn you, this is much worse than applying a patch to a third party library, and this is much much worse than creating your own CMake script. I woudln't recommend it to anyone. Also it deals with the worst part of CMake.
You can inject a CMake file in a script using the cmd with CMAKE_PROJECT_INCLUDE:
cmake .. -DCMAKE_PROJECT_INCLUDE=myfile.cmake
In myfile.cmake, you can write cmake code.
At that point, you can patch CMake builtin command with a macro to catch the unwanted behaviour and replace it with the wanted one.
macro(link_libraries)
# find and replace in ARGV
endmacro()
If you cannot write a CMake file replacing CMake commands, I will assume your filesystem is immutable and your bug cannot be fixed ;)
|
69,816,903 | 69,816,955 | How to loop the getline function in C++ | Can anyone explain to me why my getline() statement from my code is not looping as I could expect, I want the code inside the while loop to execute forever but then my code only loops the code but skips the getline() function. I'll provide the screenshot...my code is:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
while(true)
{
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
cout << "Age: " << age << "\tName: " << name << "\n\n";
}
}
the output loops only the cin function and no solution I have found so far that put things clear. My code runs like:
| Try this:
while(true)
{
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
cout << "Age: " << age << "\tName: " << name << "\n\n";
cin.get(); //<-- Add this line
}
Edit:
std::cin.ignore(10000, '\n'); is a safer solution since if you use cin.get(); and type "19 " or other combinations for age, the problem will repeat itself.
Thanks to @scohe001
Final:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main()
{
int age;
string name;
while(true)
{
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
cout << "Age: " << age << "\tName: " << name << "\n\n";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
Thanks to @user4581301
|
69,817,327 | 69,817,369 | What is the difference between these two snippets of c++ code | These are my answers for a codeforces problem and I don't know why the first snippet gives a wrong answer.
The second is accepted though.
I want to know if there is a problem with the judgment test cases because they seem to give the same output.
The problem says the following:
Given the boundaries of 2 intervals. Print the boundaries of their intersection.
Note: Boundaries mean the two ends of an interval which are the starting number and the ending number.
Input:
Only one line contains two intervals [l1,r1], [l2,r2] where (1≤l1,l2,r1,r2≤109), (l1≤r1,l2≤r2).
It's guaranteed that l1≤r1 and l2≤r2.
Output:
If there is an intersection between these 2 intervals print its boundaries , otherwise print -1.
Snippet 1
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a, b, c, d;
int z;
cin >> a >> b >> c >> d;
if(a > b)
{
z = a;
a = b;
b = z;
}
if(c > d)
{
z = c;
c = d;
d = z;
}
if(c > b)
{
cout << -1;
}
else
{
cout << max(a, c) << " " << min(b, d);
}
return 0
}
Snippet 2
#include <bits/stdc++.h>
using namespace std;
int main()
{
int l1 , r1 , l2 , r2;
cin >> l1 >> r1 >> l2 >> r2;
int _begin = max(l1,l2);
int _end = min(r1,r2);
if (_begin > _end)
cout << -1;
else
cout << begin << " " << end;
return 0;
}
| In the first program you are checking only one condition
if(c > b)
{
cout << -1;
}
But you need to check also the following condition
if ( d < a )
{
cout << -1;
}
For example
if(c > b || d < a )
{
cout << -1;
}
else
{
//...
}
|
69,817,496 | 69,941,966 | DLL reference vs DLL Implicit Linking | I just recently learn about linking an executable to a DLL either through implicit linking or explicit linking; however, it got me confused with project (or DLL) reference.
Why use implicit linking when you can add it as a reference in Visual Studio? Implicit linking requires you to export function by marking it __declspec(dllimport) in the header file in order to use it. On the other hand, if you add a project library as references, you can just use #include "header.h" and use the function like that from the DLL. What is the point of having this feature?
|
Why use implicit linking when you can add it as a reference in Visual
Studio?
Visual studio does implicit linking under the hood, when you reference it, as far as my knowledge goes. I think you're a bit confused about these 2 ways. Let me explain this clearly and separately:
Implicit Linking:
Here, you have a set of translation units, which gets compiled into a shared library(.dll on windows). And a .lib file is produced along with that. That .lib file contains the function pointer declarations and the definitions of these functions lie inside the .dll. When you link that .lib file, the application will automatically look over the .dll in its path. If it finds that, it will load that. Once the .dll is loaded, you can use any function within that .dll, as you linked with the .lib. Note that the functions which are marked as "__declspec(dllexport)" will be "exported".
So how Implicit Linking is useful?
Multiple applications can load a .dll, if you have same code that is shared between the applications, you can slap that in the .dll.
It makes using the .dll easier, but it comes at a cost, you cannot "reload" this unlike Explicit Linking.
Explicit Linking:
In this case, even if you produce the .lib, you don't link with it. Rather you use the Win32API(Or your OS's API) to load the shared library. On windows you use LoadLibrary("Path/To/The/DLLFile.dll"). Which gives you a HMODULE object. Then you retrieve the function pointers manually with the function GetProcAdress(sHMODULE, "Function Name"). Lastly, you call FreeLibrary(sHMODULE). to unload the library. Note that this happens at the runtime. In this case too you have to mark your functions with "__declspec(dllexport)".
So how Explicit Linking is useful?
In Game engines which has C++ scripting support(like Unreal) they use explicit linking to hot reload the scripting code.
If you want to have a plugin system in your application
|
69,817,743 | 69,817,782 | Skipping every M elements when iterating through an array in CUDA | I am new to Cuda programming and I have been trying to figure out how to convert the following code into Cuda code.
for (int i = 0; i <= N; i += M)
{
output[i].x = signal[i].x;
output[i].y = signal[i].y;
}
following a vector_add example, I was able to get this:
__global__ void dec(const complex * signal, int N, int M, complex * output)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i <= N)
{
output[i].x = signal[i].x;
output[i].y = signal[i].y;
}
And this is where I am stuck. In my understanding, all thread/units would calculate in parallel, so I wasn't sure where to inform the iterator to skip every M elements in Cuda. An alternative I thought of was to check i % M == 0. But I'd like to see if there is anything else I should know first to tackle this problem, such as thread syncing and etc.
Any help is appreciated.
| Something like this should work:
__global__ void dec(const complex * signal, int N, int M, complex * output)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
i *= M; // add this line
if (i <= N)
{
output[i].x = signal[i].x;
output[i].y = signal[i].y;
}
You should also make sure that you don't overflow the int variable. This should be possible to manage by not launching unnecessary threads, i.e. don't launch a grid of significantly more than N/M threads.
|
69,817,841 | 69,832,778 | SDL2 PointInRect If Statement not working | I'm making a little game as a small project but I can't get an if statement to do anything. If I make it !statement it works though. I run this if statement to find which cube on the "grid" (An array or cubes I render in a for loop I didn't show) the mouse clicked on. I use C++ and SDL2 on a Mac. This is my code:
#include <iostream>
#include <SDL2/SDL.h>
void RenderRects(SDL_Renderer *renderer);
void ToggleRect(int MouseX, int MouseY);
struct Grid
{
bool IsActive;
SDL_Rect Rect;
};
Grid grid[228960];
int main()
{
bool IsRunning = true;
bool IsRunningSim;
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window *window = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 780, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
int h, w;
SDL_MaximizeWindow(window);
SDL_GetRendererOutputSize(renderer, &w, &h);
while (IsRunning)
{
// std::cout << w << std::endl;
// std::cout << h << std::endl;
SDL_Event ev;
while (SDL_PollEvent(&ev))
{
if (ev.type == SDL_QUIT)
{
IsRunning = false;
}
if (ev.type == SDL_MOUSEBUTTONDOWN)
{
int x, y;
SDL_GetMouseState(&x, &y);
ToggleRect(x, y);
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
//rendering
RenderRects(renderer);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
void RenderRects(SDL_Renderer *renderer)
{
for (int i = 0; i < 1440; i += 10)
{
for (int j = 0; j < 795; j += 10)
{
SDL_Rect Rect = {i, j, 10, 10};
grid[i].Rect = Rect;
SDL_SetRenderDrawColor(renderer, 100, 100, 100, 225);
SDL_RenderDrawRect(renderer, &grid[i].Rect);
}
}
}
void ToggleRect(int MouseX, int MouseY)
{
SDL_Point MousePos;
MousePos.x = MouseX;
MousePos.y = MouseY;
for (int i = 0; i < 228961; i++)
{
if (SDL_PointInRect(&MousePos, &grid[i].Rect)) //This is the if that doesn't work.
{
std::cout << i << std::endl;
}
}
}
| I have fixed this. I had to change my method of drawing since it was drawing over the rect and then showing after I changed its color. There was also an issue with generating the Rects that was probably effect it.
|
69,818,651 | 69,819,040 | Using standard layout types to communicate with other languages | This draft of the standard contains a note at 11.2.6 regarding standard layout types :
[Note 3: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in [class.mem]. — end note]
Following the link to class.mem we find rules regarding the layout of standard-layout types starting here but it is not clear to me what about them makes them useful for communicating with other languages. It all seems to be about layout-compatible types and common initial sequence, but I see no indication that these compatibility requirements extend being a given implementation.
I always assumed that standard layout types could not have arbitrary padding imposed by an implementation and had to follow an "intuitive" layout which would make them easy to use from other languages. But I can't seem to find any such rules.
What does this note mean? Did I miss any rules that force standard layout types to at least be consistent across a given platform?
| The standard can’t meaningfully speak about other languages and implementations: even if one could unambiguously define “platform”, all it can do is constrain a C++ implementation, possibly in a fashion that would be impossible to satisfy for whatever arbitrary choices that other software makes. That said, the ABI can define such things, and standard-layout types are those that don’t have anything “C++-specific” (like references, base class subobjects, or a virtual table pointer) that would presumably fail to map into some other environment. In practice that “other environment” is just C, or some other language that itself follows C rules (e.g., ctypes in Python).
|
69,818,739 | 69,818,774 | C++ class instances returned by value not acting like rvalues | I had an interesting typo in some code the other day which led to a lengthy and frustrating debugging session, before I finally noticed the stray character on a much earlier line. The issue was that I had a stray '-' in my code, which the compiler was turning into a call to unary .operator-() on a member variable many lines further down in the code (below some mid-function comment blocks), and was then performing an assignment into the temporary variable holding the result of that operator-() call, which I had intended to actually go into the member variable itself. Net result: it was as if the assignment wasn't being performed at all, because it was silently being stored into a temporary.
I've simplified the issue into a minimum viable code demonstration, here, which generates no compile warnings or errors on either modern gcc or modern clang (but is untested in MSVC):
#include <stdio.h>
class foo
{
public:
int x;
foo(): x(0) {}
foo( int x_in ): x(x_in) {}
foo operator-() const { return foo(-x); }
};
int main( int argc, char** argv )
{
foo a( 10 );
foo b( 20 );
a = b;
printf( "a: %d\n", a.x ); // a: 20
a = foo( 10 );
{
}- // oops
a = b; // assigns the value '20' into the temporary storage holding '-a'
printf( "a: %d\n", a.x ); // a: 10
return 0;
}
My feeling is that the parsed '-a' should be treated as an rvalue, as it would be if 'a' was defined as an int rather than as a class, and the attempted assignment should generate a compile error, but it doesn't seem to do that in practice.
My first thought about how to guard against this was to change the function signature from foo operator-() const to const foo operator-() const, so at least compilers will complain if I try to assign a value to a generated temporary again. Does anybody have a better solution, here, or an argument that it's not an issue I should be guarding against?
|
if 'a' was defined as an int rather than as a class, and the attempted assignment should generate a compile error
Class types behave differently with build-in types in this case, the copy assignment operator is allowed to be called on the temporary object here.
As you said, you can change the return type of operator- to const foo. Or you can qualify the copy assignment operator (and move assignment operator if necessary) with lvalue-reference (since C++11) to prevent assignment on rvalues.
class foo
{
public:
int x;
foo(): x(0) {}
foo( int x_in ): x(x_in) {}
foo operator-() const { return foo(-x); }
foo& operator=(const foo&) & = default;
};
|
69,818,770 | 69,819,170 | Byte allocation different for dynamic vs. static char array of same size? | So, I ran this code in my IDE. Can anyone explain the reason why the same amount of memory isn't allocated to both of these arrays when they should be the same size?
char* dynamicCharArr = new char[15]; //allocates 8 bytes
cout << sizeof(dynamicCharArr) << endl;
char staticCharArr[15]; //allocates 15 bytes
cout << sizeof(staticCharArr) << endl;
| new[] returns a pointer to the memory it allocates. You are printing the size of the pointer itself, not the size of the allocated memory being pointed at.
There is no way for sizeof() to query the size of that allocated memory. If you pass in the pointer itself, you get the size of the pointer. If you pass in the dereferenced pointer, you get the size of 1 element of the array, not the whole array. In that latter case, you would have to multiply that size by the element count that you pass to new[].
In both examples, the amount of memory accessible to your code is sizeof(char) * 15. But you simply can't obtain that value from a pointer alone, which is why sizeof(dynamicCharArr) doesn't work. In a fixed array, the size is part of the array's type, which is why sizeof(staticCharArr) does work.
However, note that the physical memory allocated by new[] for a dynamic array will always be slightly larger than the memory used by a fixed array of the same element count, because new[] allocates additional internal metadata that is used by delete[], and even the memory manager itself. That metadata will include (amongst whatever else the memory manager needs internally, like debug info, block tracking, etc) the number of elements that new[] allocated, so delete[] knows how many elements to destroy. But sizeof() doesn't know (or care about) that metadata.
|
69,818,875 | 69,818,909 | Avoiding circular references with forward declarations, but unable to access class members | So, I've got several classes, two of which need to reference each other. I solved circular references with forward declarations in Entity.h, just included Entity.h in my Timeline.h class declaration. Entity has a subclass Human which would hopefully call a method in Timeline which is timeline->addEvent(...).
Timeline.h
#include <queue>
#include "Event.h"
class Timeline {
private:
std::priority_queue<Event> events;
long unsigned int currentTime = 0;
public:
Timeline() = default;
~Timeline() = default;
void addEvent(long unsigned int timestamp, EventType type, Entity *entity);
void processEvent();
void getCurrentTime();
};
Event.h
#include "Entity.h"
class Event {
private:
long unsigned int timestamp;
EventType type;
Entity *entity;
public:
Event(long unsigned int timestamp, EventType type, Entity *entity);
~Event() = default;
long unsigned int getTimestamp();
EventType getType();
Entity *getEntity();
bool operator<(const Event &rhs) const;
bool operator>(const Event &rhs) const;
bool operator<=(const Event &rhs) const;
bool operator>=(const Event &rhs) const;
};
Entity.h
class Event;
class Timeline;
class Entity {
protected:
Timeline *timeline;
long unsigned int currTimestamp;
public:
explicit Entity(Timeline *timeline, unsigned int age);
virtual void processEvent(Event event) = 0;
};
Human.cpp (calls timeline->addEvent(...))
void Human::sleep(Event event) {
Animal::sleep(event);
unsigned int timeBlock = 96;
this->timeline->addEvent(this->currTimestamp + timeBlock, EventType::AWAKEN, this);
}
And error logs
error: invalid use of incomplete type ‘class Timeline’
this->timeline->addEvent(this->currTimestamp + timeBlock, EventType::AWAKEN, this);
note: forward declaration of ‘class Timeline’
class Timeline;
I guess I'm just confused on why this would be an issue. It was fine using forward declaration when it was just class Event; but as soon as class Timeline; was added in order to implement addEvent() to Entity, it goes full fail. Any suggestions?
| Forward declaration only works if you have pointer member, but not actually trying to dereference it.
From a look at your code structure, if Human is subclass of Entity, then in the source code of Human.cpp where you dereference the pointer to Timeline, you need to actually include Timeline.h (instead of fw declaration of it).
|
69,819,729 | 69,872,284 | Creating a thread safe atomic counter | I have a specific requirement in one of the my projects, that is keeping "count" of certain operations and eventually "reading" + "resetting" these counters periodically (eg. 24 hours).
Operation will be:
Worker threads -> increment counters (randomly)
Timer thread (eg. 24 hours) -> read count -> do something -> reset counters
The platform I am interested in is Windows, but if this can be cross platform even better. I'm using Visual Studio and target Windows architecture is x64 only.
I am uncertain if the result is "ok" and if my implementation is correct. Frankly, never used much std wrappers and my c++ knowledge is quite limited.
Result is:
12272 Current: 2
12272 After: 0
12272 Current: 18
12272 After: 0
12272 Current: 20
12272 After: 0
12272 Current: 20
12272 After: 0
12272 Current: 20
12272 After: 0
Below is a fully copy/paste reproducible example:
#include <iostream>
#include <chrono>
#include <thread>
#include <Windows.h>
class ThreadSafeCounter final
{
private:
std::atomic_uint m_Counter1;
std::atomic_uint m_Counter2;
std::atomic_uint m_Counter3;
public:
ThreadSafeCounter(const ThreadSafeCounter&) = delete;
ThreadSafeCounter(ThreadSafeCounter&&) = delete;
ThreadSafeCounter& operator = (const ThreadSafeCounter&) = delete;
ThreadSafeCounter& operator = (ThreadSafeCounter&&) = delete;
ThreadSafeCounter() : m_Counter1(0), m_Counter2(0), m_Counter3(0) {}
~ThreadSafeCounter() = default;
std::uint32_t IncCounter1() noexcept
{
m_Counter1.fetch_add(1, std::memory_order_relaxed) + 1;
return m_Counter1;
}
std::uint32_t DecCounter1() noexcept
{
m_Counter1.fetch_sub(1, std::memory_order_relaxed) - 1;
return m_Counter1;
}
VOID ClearCounter1() noexcept
{
m_Counter1.exchange(0);
}
};
int main()
{
static ThreadSafeCounter Threads;
auto Thread1 = []() {
while (true)
{
auto test = Threads.IncCounter1();
std::cout << std::this_thread::get_id() << " Threads.IncCounter1() -> " << test << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
};
auto Thread2 = []() {
while (true)
{
auto test = Threads.DecCounter1();
std::cout << std::this_thread::get_id() << " Threads.DecCounter1() -> " << test << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
};
auto Thread3 = []() {
while (true)
{
Threads.ClearCounter1();
std::cout << std::this_thread::get_id() << " Threads.ClearCounter1()" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
};
std::thread th1(Thread1);
std::thread th2(Thread2);
std::thread th3(Thread3);
th1.join();
th2.join();
th3.join();
}
I should mention that in my real life project there is no usage of std::thread wrapper, and the threads are created using WinApi functions like CreateThread. The above is just to simulate/test the code.
Please point out to me what is wrong with the above code, what could be improved and if I'm on the right direction at all.
Thank you!
| Why are you writing a ThreadSafeCounter class at all?
std::atomic<size_t> is a ThreadSafeCounter. That's the whole point of std::atomic. So you should use it instead. No need for another class. Most atomics have operator++/operator-- specializations, so your main loop could easily be rewritten like this:
static std::atomic_int ThreadCounter1(0);
auto Thread1 = []() {
while (true)
{
auto test = ++ThreadCounter1; // or ThreadCounter1++, whatever you need
std::cout << std::this_thread::get_id() << " Threads.IncCounter1() -> " << test << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
};
auto Thread2 = []() {
while (true)
{
auto test = --ThreadCounter1;
std::cout << std::this_thread::get_id() << " Threads.DecCounter1() -> " << test << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
};
auto Thread3 = []() {
while (true)
{
/* Note: You could simply "ThreadCounter1 = 0" assign it here.
But exchange not only assigns a new value, it returns the previous value.
*/
auto ValueAtReset=ThreadCounter1.exchange(0);
std::cout << std::this_thread::get_id() << " Threads.ClearCounter1() called at value" << ValueAtReset << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
};
I forgot to mention a problem with your DecCounter operation. You are using atomic_uint, which cannot handle negative numbers. But there is no guarantee, that your Thread2 will not run (aka decrement the counter) before Thread1. Which means that your counter will wrap.
So you could/should use std::atomic<int> instead. That will give you the correct number of (calls_Thread1 - calls_Thread2). The number will get negative if Thead2 has decremented the value more often than Thread1.
|
69,819,844 | 69,820,202 | Which stage in C/C++ compilation process makes it system-dependend? | Am going through this tutorial. Is only the linking stage that makes the compilation of c/c++ code system dependent? Isn't assembly language code generation also system dependent? Isn't system, machine and processor the same thing in this context?
| I guess you mean this bit:
Linking is very system-dependent, so the easiest way to link object files together is to call clang on all of the different files that you wish to link together.
What they mean is that the command-line syntax of linking is very system-dependent. You may have to tell the linker explicitly what standard library files should be included, for instance, which varies across platforms. But on all platforms, the clang frontend knows how to invoke the linker correctly. The tutorial is advising you to link via clang instead of invoking the linker directly.
This is certainly not the only system-dependent part of compilation, but other parts are better hidden. Passing a flag like -O2 to clang enables all sorts of CPU-dependent program transformations, but you don't have to tell clang on the command line how to do them.
|
69,820,220 | 69,823,386 | Jumping into C++: Ch 5 Problem 7 using vertical bar graph | I am in need of assistance to create an vertical bar graph with required limitations of learning experience. Such as, using only the fundamental basics listed: if statement, boolean, loop, string, arithmetic and comparison operators. Basically giving an idea of how limited my experience is in the language for clarification. Now, I have completed this problem already but the output does not seem to look like a desirable graph in my opinion so this is why posting. I will provide the problem and valid code I used to complete this problem.
Write a program that provides the option of tallying up the results of a poll with 3 possible
values. The first input to the program is the poll question; the next three inputs are the possible
answers. The first answer is indicated by 1, the second by 2, the third by 3. The answers are
tallied until a 0 is entered. The program should then show the results of the poll—try making a
bar graph that shows the results properly scaled to fit on your screen no matter how many
results were entered.
#include<iostream>
int main()
{
bool poll = false;
int Tech = 0, Edu = 0, Agri = 0;
std::cout << "VOTING POLL" << std::endl;
std::cout << "----------------------------" << std::endl;
std::cout << "----------------------------" << std::endl;
while(!poll)
{
std::cout << "Of the year 2022, in the United States of America, what should be the top priority of our concerns?" << std::endl;
std::cout << " 1.Technology\n 2.Education\n 3.Agriculture" << std::endl;
std::cout << "\n";
int pollAnswer;
std::cin >> pollAnswer;
if(pollAnswer == 1)
{
Tech++;
}
else if(pollAnswer == 2)
{
Edu++;
}
else if(pollAnswer == 3)
{
Agri++;
}
else if(pollAnswer == 0)
{
poll = true;
}
else
{
std::cout << "\n" << "Invalid. Please choose an answer from the above listing." << std::endl;
}
}
std::cout << "Technology: ";
while(Tech > 0)
{
std::cout << "* ";
Tech--;
}
std::cout << std::endl;
std::cout << "Education: ";
while(Edu > 0)
{
std::cout << "# ";
Edu--;
}
std::cout << std::endl;
std::cout << "Agriculture: ";
while(Agri > 0)
{
std::cout << "| ";
Agri--;
}
}
|
using only the fundamental basics listed: if statement, boolean, loop, string, arithmetic and comparison operators.
Those are enough to write a sort of scanline algorithm:
Establish a maximum height for the bars and scale all the (three) values accordingly. This isn't mentioned in your requirements, but it seems better to avoid too high (or too low) bars.
for each line of output (you may initialize a loop variable row at max_height and decrease it down to 0):
print some spaces, so that you can add the labels after this loop.
if the value of the first scaled variable (say, Tech) is less than or equal to row, print a ' ' (a space) otherwise print the character chosen to represent that bar ('*', I think).
repeat for all the other bars and then add a '\n' (newline) to end this row.
Print the labels, like "Technology" and the likes, correctly spaced.
I'll leave all the details of the implementation to the reader.
|
69,820,402 | 69,820,907 | How to Retrieve a Scalar Value from a Compute Function in Apache Arrow | In am looping over the elements of an Arrow Array and trying to apply a compute function to each scalar that will tell me the year, month, day, etc... of each element. The code looks something like this:
arrow::NumericArray<arrow::Date32Type> array = {...}
for (int64_t i = 0; i < array.length(); i++) {
arrow::Result<std::shared_ptr<arrow::Scalar>> result = array->GetScalar(i);
if (!result.ok()) {
// TODO: handle error
}
arrow::Result<arrow::Datum> year = arrow::compute::Year(*result);
}
However, I am not really clear as to how to extract the actual int64_t value from the arrow::compute::Year call. I have tried to do things like
const std::shared_ptr<int64_t> val = year.ValueOrDie();
>>> 'arrow::Datum' to non-scalar type 'const std::shared_ptr<long int>' requested
I've tried similarly to assign to just an int64_t which also fails with error: cannot convert 'arrow::Datum' to 'int64_t'
I didn't see any method of the Datum class that would otherwise return a scalar value in the primitive type that I think arrow::compute::Year should be returning. Any idea what I might be misunderstanding with the Datum / Scalar / Compute APIs?
| Arrow's compute functions are really meant to be applied on arrays and not scalars, otherwise the overhead renders the operation rather inefficient. The arrow::compute::Year function takes in a Datum. This is a convenience item that could be a Scalar, an Array, ArrayData, RecordBatch, or Table. Not all functions accept all possible values of Datum (in particular, many do not accept RecordBatch or Table).
Once you have a result, there are a few ways you can get the data, and grabbing individual scalars is probably going to be the least efficient, especially if you know the type of the data ahead of time (in this case we know the type will be int64_t). This is because a scalar is meant to be a type-erased wrapper (e.g. like an "object" in python or java) around some value and it carries some overhead.
So my suggestion would be:
// If you are going to be passing your array through the compute
// infrastructure you'll need to have it in a shared_ptr.
// Also, NumericArray is a base class so you don't often need
// to refer to it directly. You'll typically be getting one of the
// concrete subclasses like Date32Array
std::shared_ptr<arrow::Date32Array> array = {...}
// A datum can be implicitly constructed from a shared_ptr to an
// array. You could also explicitly construct it if that is more
// comfortable to you. Here `array` is being implicitly cast to a Datum.
ARROW_ASSIGN_OR_RAISE(arrow::Datum year_datum, arrow::compute::Year(array));
// Now we have a datum, but the docs tell us the return value from the
// `Year` function is always an array, so lets just unwrap it. This is
// something that could probably be improved in Arrow (might as well
// return an array)
std::shared_ptr<arrow::Array> years_arr = year_datum.make_array();
// Also, we know that the data type is Int64 so let's go ahead and
// cast further
std::shared_ptr<arrow::Int64Array> years = std::dynamic_pointer_cast<arrow::Int64Array>(years_arr);
// The concrete classes can be iterated in a variety of ways. GetScalar
// is the least efficient (but doesn't require knowing the type up front)
// Since we know the type (we've cast to Int64Array) we can use Value
// to get a single int64_t, raw_values() to get a const int64_t* (e.g a
// C-style array) or, perhaps the simplest, begin() and end() to get STL
// compliant iterators of int64_t
for (int64_t year : years) {
std::cout << "Year: " << year << std::endl;
}
If you really want to work with scalars:
arrow::Array array = {...}
for (int64_t i = 0; i < array.length(); i++) {
arrow::Result<std::shared_ptr<arrow::Scalar>> result = array->GetScalar(i);
if (!result.ok()) {
// TODO: handle error
}
ARROW_ASSIGN_OR_RAISE(Datum year_datum, arrow::compute::Year(*result));
std::shared_ptr<arrow::Scalar> year_scalar = year_datum.scalar();
std::shared_ptr<arrow::Int64Scalar> year_scalar_int = std::dynamic_pointer_cast<arrow::Int64Scalar>(year_scalar);
int64_t year = year_scalar_int->value;
}
|
69,821,036 | 69,821,116 | Which header file or definitions to use for using char8_t data type in C++? | So I want to use char8_t data type in my code. But my compiler shows me that it could not find an identifier like char8_t , which probably means it could not find required header file or definitions for it.
So can anyone tell me what header files / definitions should I use to get the char8_t data type? The language is C++. I'll be thankful if you can also answer for C.
PS:<cwchar> did not work.
Edit:
My code:
#include <iostream>
#include <cwchar>
using namespace std;
int main()
{
char c='a';
wchar_t w=L'A';
char8_t c8=u8'c';
char16_t c16=u'D';
char32_t c32=U'K';
cout<<"Data Type"<<"\t"<<"Size"<<"\n"
<<"char"<<"\t \t"<<sizeof(c)<<" bytes"<<"\n"
<<"wchar_t"<<"\t \t"<<sizeof(w)<<" bytes"<<"\n"
<<"char8_t"<<"\t"<<sizeof(c8)<<"\n"
<<"char16_t"<<"\t"<<sizeof(c16)<<" bytes"<<"\n"
<<"char32_t"<<"\t"<<sizeof(c32)<<" bytes"<<"\n";
return 0;
}
My compiler throws this error:
WideCharacters.cpp: In function 'int main()':
WideCharacters.cpp:8:5: error: 'char8_t' was not declared in this
scope; did you mean 'wchar_t'?
8 | char8_t c8=u8'c';
| ^~~~~~~
| wchar_t
WideCharacters.cpp:15:31: error: 'c8' was not declared in this
scope; did you mean 'c'?
15 | <<"char8_t"<<"\t"<<sizeof(c8)<<"\n"
| ^~
| c
Edit-2:
I have my C++ standard set to C++20 in VS code so there is no problem with standard.
| char8_t is a keyword. It's built into the language, so you don't need any headers.
If it doesn't work, either your compiler doesn't support it, or you forgot to enable C++20 support (e.g. -std=c++20 in GCC).
|
69,821,511 | 69,821,761 | sequence-point warning using pack expansion when assigning to tuple | // https://godbolt.org/z/e7ebq6hYE
int print(std::string str, int i){
std::cout << i << str << std::endl;
return i;
}
template<typename ... Args>
void concat(Args ... args) {
int i = 2;
std::tuple<int, int, int, int> ret { print("ss", -22), print(args, i++) ... }; // gcc warning
std::vector<int> ret1 { print("ss", -22), print(args, i++) ... };
}
int main()
{
concat("a", "b", "c");
}
warning: operation on 'i' may be undefined [-Wsequence-point]
For the above code only gcc seem to think there is an issue with i++ in pack expansion, and only when the assignment is for a tuple. clang seems to compile and run without warnings.
Is it a bug in gcc or is clang not reporting this warning?
| The warning is wrong, see rule (10) here:
In list-initialization, every value computation and side effect of a given initializer clause is sequenced before every value computation and side effect associated with any initializer clause that follows it in the brace-enclosed comma-separated list of initalizers.
The rule should equally affect brace initiailization of tuples and vectors.
Note that this is not a fold expression, just a pack expansion.
|
69,821,744 | 69,821,964 | Assigning a char value to an int | I am a beginner in C++, and I saw this function below for adding a word to a trie, and got confused on the line I commented with a question mark. Is the author assigning a char value to an int here? What int value would be assigned?
struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];
// isEndOfWord is true if the node represents
// end of a word
bool isEndOfWord;
};
void insert(struct TrieNode *root, string key)
{
struct TrieNode *pCrawl = root;
for (int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a'; // ?
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
// mark last node as leaf
pCrawl->isEndOfWord = true;
}
| char is just a 1-byte number. The computer encodes those numbers to a character using whatever character encoding your computer uses (mostly ASCII).
In ASCII, a has a value of 97, b has a value of 98, ... , z has a value of 122
So:
If key[i] is "a", value = 97 - 97 = 0
If key[i] is "b", value = 98 - 97 = 1
If key[i] is "c", value = 99 - 97 = 2
...
If key[i] is "z", value = 122 - 97 = 25
So, you can see, this is a "trick" to map all the values of key[i] from 0 to 25
|
69,821,782 | 69,822,081 | reinterpret_cast and explicit alignment requirement | Given this (bold part) about reinterpret_cast, I was expecting that the piece of code below would generate different addresses when casting X* to Y* since the latter is more striclty aligned than the former. What am I missing here?
Any object pointer type T1* can be converted to another object pointer type cv T2*. This is exactly equivalent to static_cast<cv T2*>(static_cast<cv void*>(expression)) (which implies that if T2's alignment requirement is not stricter than T1's, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value)
cppreference/reinterpret_cast
#include <iostream>
struct alignas (1) X
{
char c;
};
struct alignas (32) Y
{
char c;
};
int main(int argc, const char *const* const argv)
{
std::cout << alignof(X) << " " << alignof(Y) << std::endl;
X x;
Y y;
std::cout << &x << " " << reinterpret_cast<Y*>(&x) << std::endl;
std::cout << &y << " " << reinterpret_cast<X*>(&y) << std::endl;
}
output
Program returned: 0
1 32
0x7ffef3434578 0x7ffef3434578
0x7ffef3434540 0x7ffef3434540
snippet on godbolt
| Quoting from [expr.reinterpret.cast]/7:
An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_cast<cv T*>(static_cast<cv void*>(v)).
Then, from [expr.static.cast]/13:
A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified....
I believe these rules apply here. In your case, reinterpret_cast<Y*>(&x) is resolved as static_cast<Y*>(static_cast<void*>(&x)). The original pointer value static_cast<void*>(&x) represents the address A and this address generally does not satisfy the alignment requirements of Y.
Consequently, the value of the resulting pointer is unspecified.
|
69,821,876 | 70,493,457 | How to decode AAC network audio stream using ffmpeg | I implemented a network video player (like VLC) using ffmpeg. But it can not decode AAC audio stream received from a IP camera. It can decode other audio sterams like G711, G726 etc. I set the codec ID as AV_CODEC_ID_AAC and I set channels and sample rate of AvCodecContext. But avcodec_decode_audio4 fails with an error code of INVALID_DATA. I checked previously asked questions, I tried to add extrabytes to AvCodecContext using media format specific parameters of "config=1408". And I set extradatabytes as 2 bytes of "20" and "8" but it also not worked. I appreciate any help, thanks.
IP CAMERA SDP:
a=rtpmap:96 mpeg4-generic/16000/1
a=fmtp:96 streamtype=5; profile-level-id=5; mode=AAC-hbr; config=1408; SizeLength=13; IndexLength=3; IndexDeltaLength=3
AVCodec* decoder = avcodec_find_decoder((::AVCodecID)id);//set as AV_CODEC_ID_AAC
AVCodecContext* decoderContext = avcodec_alloc_context3(decoder);
char* test = (char*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi("1408").ToPointer();
unsigned int length;
uint8_t* extradata = parseGeneralConfigStr(test, length);//it is set as 0x14 and 0x08
decoderContext->channels = number_of_channels; //set as 1
decoderContext->sample_rate = sample_rate; //set as 16000
decoderContext->channel_layout = AV_CH_LAYOUT_MONO;
decoderContext->codec_type = AVMEDIA_TYPE_AUDIO;
decoderContext->extradata = (uint8_t*)av_malloc(AV_INPUT_BUFFER_PADDING_SIZE + length);
memcpy(decoderContext->extradata, extradata, length);
memset(decoderContext->extradata+ length, 0, AV_INPUT_BUFFER_PADDING_SIZE);
| Did you check data for INVALID_DATA?
You can check it according to RFC
RFC3640 (3.2 RTP Payload Structure)
AAC Payload can be seperated like below
AU-Header | Size Info | ADTS | Data
Example payload 00 10 0c 00 ff f1 60 40 30 01 7c 01 30 35 ac
According to configs that u shared
AU-size (SizeLength=13)
AU-Index / AU-Index-delta (IndexLength=3/IndexDeltaLength=3)
The length in bits of AU-Header is 13(SizeLength) + 3(IndexLength/IndexDeltaLength) = 16.
AU-Header 00 10
You should use AU-size(SizeLength) value for Size Info
AU-size: Indicates the size in octets of the associated Access Unit in the Access Unit Data Section in the same RTP packet.
First 13 (SizeLength) bits 0000000000010 equals to 2. So read 2 octets for size info.
Size Info 0c 00
ADTS ff f1 60 40 30 01 7c
ADTS Parser
ID MPEG-4
MPEG Layer 0
CRC checksum absent 1
Profile Low Complexity profile (AAC LC)
Sampling frequency 16000
Private bit 0
Channel configuration 1
Original/copy 0
Home 0
Copyright identification bit 0
Copyright identification start 0
AAC frame length 384
ADTS buffer fullness 95
No raw data blocks in frame 0
Data starts with 01 30 35 ac.
|
69,822,870 | 69,823,063 | Must `throw nullptr` be caught as a pointer, regardless of pointer type? | The following program throws nullptr and then catches the exception as int*:
#include <iostream>
int main() {
try {
throw nullptr;
}
catch(int*) {
std::cout << "caught int*";
}
catch(...) {
std::cout << "caught other";
}
}
In Clang and GCC the program successfully prints caught int*, demo: https://gcc.godbolt.org/z/789639qbb
However in Visual Studio 16.11.2 the program prints caught other. Is it a bug in MSVC?
| Looks like a bug in Visual Studio, according to the standard [except.handle]:
A handler is a match for an exception object of type E if
[...]
the handler is of type cv T or const T& where T is a pointer or pointer-to->member type and E is std::nullptr_t.
|
69,823,031 | 69,825,104 | Converting LPCSTR to LPCWSTR in C++, ATL not available | Before I start,
Please do understand that this question is not a duplicate. There are questions out there with the same header :
Convert LPCSTR to LPCWSTR
However, I did some research before asking this question and came across ATL or Active Template Library.
However the compiler I use, doesn't come with ATL, which does not allow me to convert from LPCSTR to LPCWSTR.
Also, to understand why I need to convert these two datatypes, the reason is that I am working on a project, which is actually a Console Game Engine.
In case you don't know, to rename a console window, you need to use SetConsoleTitle(LPCWSTR winName)
And at first, I used LPCWSTR datatype as an argument for my function. But, when I tried another function, which is actually a drawing function, this is what happens:
This combination of UNICODE characters that you see here, is a function for drawing a rectangle on the console. The rectangle correctly displays, however, there is some text, or should I say, the Console Title itself, displayed across the rectangle.
I did not add any such thing of displaying the console title on the rectangle, nor did I mess up my code in any way. I burned through my code a few times, and there was nothing wrong, however, somehow, the console title is displayed on the rectangle.
I somehow think that this is related to the LPCWSTR datatype, because when I tried the function, SetConsoleTitle() manually
Help me find a solution, will you?
| Since the title is usually constant, you can simply call
SetConsoleTitle(L"My Title"); //or
const wchar_t* title = L"My Title";
SetConsoleTitle(title);
In general, use MultiByteToWideChar to convert ANSI or UTF8, to UTF16
#include <iostream>
#include <string>
#include <windows.h>
std::wstring u16(const char* in, int codepage)
{
if (!in) return std::wstring(L"");
int size = MultiByteToWideChar(codepage, 0, in, -1, NULL, 0);
std::wstring ws(size, L'\0');
MultiByteToWideChar(codepage, 0, in, -1, ws.data(), size);
return ws;
}
int main()
{
const char* str = "My Title"; //<- ANSI string
SetConsoleTitle(u16(str, CP_ACP).c_str());
std::string s;
std::cin >> s;
str = reinterpret_cast<const char*>(u8"Ελληνικά"); //<- UTF8
SetConsoleTitle(u16(str, CP_UTF8).c_str());
std::cin >> s;
return 0;
}
Note that the title changes back when program exits.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.