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,765,484 | 69,766,659 | Parallel sieve of eratosthenes produces wrong output based on number of threads | This is the approach I'm using for parallelization:
p = Process ID, N = total number of processes, n = input size
Each process is assigned n/N numbers, ranging from index p*n/N to (p+1)*n/N-1.
When process 0 finds a prime number, all its multiples are marked in parallel.
Finally, each process counts the number of primes in its assigned range and adds it to the global count.
Using C++/OpenMP for parallelization. Before calling the function, I set the maximum number of threads with omp_set_num_threads().
// p is thread ID, N is total number of threads, n is the array size
#define LOWER_BOUND(p, N, n) p == 0 ? 2 : (p * n / N)
#define UPPER_BOUND(p, N, n) p == (N - 1) ? (n - 1) : (p + 1) * (n / N) - 1
size_t parallel_soe(std::vector<std::atomic<bool>>& A) {
size_t n = A.size();
size_t sqrt_n = sqrt(n);
for (size_t i = 2; i <= sqrt_n; i++) {
if (A[i] == true) continue;
#pragma omp parallel
{
uint16_t p = omp_get_thread_num();
uint16_t N = omp_get_num_threads();
size_t lower_bound = LOWER_BOUND(p, N, n);
size_t upper_bound = UPPER_BOUND(p, N, n);
size_t smallest_multiple = std::max(i * i, lower_bound);
size_t remainder = smallest_multiple % i;
if (remainder) smallest_multiple += i - remainder;
for (size_t j = smallest_multiple; j <= upper_bound; j += i)
A[j] = true;
}
}
// Count number of primes
size_t prime_count = 0;
#pragma omp parallel
{
uint16_t p = omp_get_thread_num();
uint16_t N = omp_get_num_threads();
size_t lower_bound = LOWER_BOUND(p, N, n);
size_t upper_bound = UPPER_BOUND(p, N, n);
size_t count = 0;
for (size_t i = lower_bound; i <= upper_bound; i++)
if (A[i] == false)
count++;
#pragma omp atomic
prime_count += count;
}
return prime_count;
}
The value returned by the function is correct when maximum threads are set to 2, 4, 8, 10, and 16, but not for 6, 12, and 14. I'm running it on a 4 core Intel i5.
This is my output log:
Finding primes under: 10000
================================
[2-parallel] Found 1229 primes in 542 microseconds
[4-parallel] Found 1229 primes in 3173 microseconds
[6-parallel] Found 1228 primes in 2353 microseconds
[8-parallel] Found 1229 primes in 3600 microseconds
[10-parallel] Found 1229 primes in 3227 microseconds
[12-parallel] Found 1227 primes in 2778 microseconds
[14-parallel] Found 1226 primes in 2248 microseconds
[16-parallel] Found 1229 primes in 2320 microseconds
Finding primes under: 100000
================================
[2-parallel] Found 9592 primes in 5186 microseconds
[4-parallel] Found 9592 primes in 10351 microseconds
[6-parallel] Found 9591 primes in 9859 microseconds
[8-parallel] Found 9592 primes in 8500 microseconds
[10-parallel] Found 9592 primes in 12294 microseconds
[12-parallel] Found 9591 primes in 8300 microseconds
[14-parallel] Found 9582 primes in 9252 microseconds
[16-parallel] Found 9592 primes in 8557 microseconds
Finding primes under: 1000000
================================
[2-parallel] Found 78498 primes in 36091 microseconds
[4-parallel] Found 78498 primes in 43570 microseconds
[6-parallel] Found 78498 primes in 48176 microseconds
[8-parallel] Found 78498 primes in 44201 microseconds
[10-parallel] Found 78498 primes in 43645 microseconds
[12-parallel] Found 78498 primes in 49175 microseconds
[14-parallel] Found 78494 primes in 47411 microseconds
[16-parallel] Found 78498 primes in 53602 microseconds
| I figured it out. It had nothing to do with parallel execution, I just had a calculation error when computing the bounds.
This is the correct formula for computing lower bound:
#define LOWER_BOUND(p, N, n) p == 0 ? 2 : p * (n / N)
Notice the paranthesis around n/n.
|
69,765,682 | 69,765,729 | Successor of INT_MAX and INT_MIN | I have 2 questions,
Is 1e9 less than INT_MAX value from the header file climits?
Is -1e9 greater than INT_MIN value from the header file climits?
and if I need to use in my program, some big positive number or smallest negative number, I use INT_MAX or INT_MIN in general
but when there's some constraints in some cases like no use of header files to write your program, in that situation, can I use 1e9 and -1e9 as largest number and smallest number?
|
Is 1e9 less than INT_MAX value from the header file climits?
It can be. It isn't necessarily. It depends on the target system.
Is -1e9 greater than INT_MIN value from the header file climits?
Same as above.
Since int isn't guaranteed to be sufficient, you should use at least long type, or the more specific aliases from <cstdint> header which are at least 32 bits wide if you need numbers in the range of [-1e9,1e9].
|
69,766,412 | 69,766,538 | How to ensure template parameter is non-const and non-reference | Often (most of the time?) when creating types with template type parameters you want to ensure the type parameter is filled in with a non-reference, unqualified (non-const, non-volatile) type. However, a simple definition like the following lets the user fill in any type for T:
template <typename T>
class MyContainer {
T* whatever;
T moreStuff;
};
Modern C++ has concepts that should be able to take care of this problem. What is the best (and preferably least boilerplate-y) way to do this?
| I'd use a concept for this.
template <typename T>
concept cvref_unqualified = std::is_same_v<std::remove_cvref_t<T>, T>;
template <cvref_unqualified T>
class MyContainer {...};
|
69,766,466 | 69,870,171 | Cython: Import definitions from .pyx file | I have 1 Cython .pxd file and 1 Cython .pyx file, the pyx file contains a cdef class:
# myclass.pyx (compiled to myclass.so)
cdef class myclass:
pass
Now is the .pxd file of another feature
# another.pxd (with another.pyx along)
from libcpp.vector cimport vector
import myclass # This line is funny, change 'myclass' to whatever and no syntax error
cdef vector[myclass] myvar # COMPILE TIME ERROR
cdef myclass myvar2 # SIMPLER, STILL COMPILE TIME ERROR
When compiling another.pyx, Cython shows error about vector[myclass], it says 'myclass' is unknown. Why is it so?
| It should be clearly described this way:
myclass.pyx is compiled into .so file
But there are 2 kinds of stuff in a .so file
Python definitions: Can be imported only with 'import'
Cython definitions: Can be imported only with 'cimport'
The problem is import myclass in another.pxd won't import myclass because it is cdef (Cython definition).
In another.pxd file, to import 'myclass', it must be either:
from myclass cimport myclass
myvar2 will be: cdef myclass myvar2
cimport myclass
myvar2 will be: cdef myclass.myclass myvar2
cimport some.path.to.myclass as myclass
myvar2 will be: cdef myclass myvar2
There may be a problem with exporting too, especially using Python build tool instead of cython3 and gcc directly:
__pyx_capi__ is not available in the .so file
myclass is not public and aren't seen after importing
Thus better put the myclass under public scope in myclass.pyx:
cdef public:
class myclass:
pass
|
69,766,887 | 69,767,011 | Declaration of class inside header file without initialization | I want to declarate a class object of Class B inside of Class A in a header file, like:
// test.h
class A {
public:
B b;
};
but lets say B has no default Constructor and the required parameters are not known yet (in header file). Which possibilities in c++ exist to declarate a class instance in another class without initializing it at that moment.
| Your example lacks any declaration of B, so you will get a compiler error. You must either add or include B's declaration, or you will need to forward declare it, e.g.
class B;
class A {
public:
B b; // Compiler error
};
However, this will still not work, since A needs to know the space to set aside for B. You may work around this, by making b a reference, pointer or smart pointer to B:
class B;
class A {
public:
A();
B* b1;
B& b2;
std::unique_ptr<B> b3;
};
For b1, b2 and b3, it is enough that you include the declaration of B in A's .cpp file and initialize the B's there:
// A.cpp
#include "A.h"
#include "B.h"
A::A() : b1(new B(<params>)), b2(<from a reference>), b3(make_unique<B>(params)
{}
Note that b1 is bad, since it uses new and needs to delete the object later, and that b3 will need a destructor defined in A.cpp (the default is fine).
|
69,767,069 | 69,767,144 | Forwarding a function to std::thread via a lambda expression | I'm working through the notes here to understand an example async function implementation.
Attempting to compile the below code
#include <future>
#include <iostream>
#include <thread>
#include <chrono>
#include <ctime>
#include <type_traits>
int f(int x) {
auto start = std::chrono::system_clock::now();
std::time_t start_time = std::chrono::system_clock::to_time_t(start);
std::cout << "returning " << x << " at " << std::ctime(&start_time) << std::endl;
return x;
}
template<typename Function, typename... Args>
auto async(Function&& function, Args&&... args) {
std::promise<typename std::result_of<Function(Args...)>::type> outer_promise;
auto future = outer_promise.get_future();
auto lambda = [function, promise = std::move(outer_promise)](Args&&... args) mutable {
try {
promise.set_value(function(args...));
} catch (...) {
promise.set_exception(std::current_exception());
}
};
std::thread t0(std::move(lambda), std::forward<Args>(args)...);
t0.detach();
return future;
}
int main() {
auto result1 = async(f, 1);
auto result2 = async(f, 2);
}
I get the following compiler errors, which I'm struggling to understand.
I'd like some guidance on why this function arg is not declared correctly according to the compiler.
In instantiation of 'async(Function&&, Args&& ...)::<lambda(Args&& ...)> mutable [with Function = int (&)(int); Args = {int}]':
22:61: required from 'struct async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]::<lambda(int&&)>'
28:3: required from 'auto async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]'
37:27: required from here
22:88: error: variable 'function' has function type
22:88: error: variable 'function' has function type
In instantiation of 'struct async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]::<lambda(int&&)>':
28:3: required from 'auto async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]'
37:27: required from here
22:18: error: field 'async(Function&&, Args&& ...) [with Function = int (&)(int); Args = {int}]::<lambda(int&&)>::<function capture>' invalidly declared function type
| To get result type of result_of you have to access type:
std::promise< typename std::result_of<Function(Args...)>::type > outer_promise;
|
69,767,320 | 69,767,405 | std::array and std::tuple in memory order | I'm testing a small code fragment and I'm surprised the same representation of 4 bytes as put into std::array and std::tuple yield different in-memory layouts
#include <iostream>
#include <tuple>
#include <array>
struct XYZW {
uint32_t x;
uint32_t y;
//std::array<uint8_t,4> z;
std::tuple<uint8_t, uint8_t, uint8_t, uint8_t> z;
uint32_t w;
};
int main() {
XYZW i;
i.z = {255, 0, 0, 0};
uint32_t z = (*reinterpret_cast<uint32_t*>(&i.z));
std::cout << z << " \n";
}
For tuple the output is: 4278190080, while for the array it is: 255.
Is this expected?
| std::array has a layout specified by the standard, but std::tuple does not, and can be anything the implementation wants.
So it's expected that they may differ, but of course they may also happen to choose the same layout, on some compilers/versions/platforms - there's just no guarantee.
In practice one of the easiest ways to implement std::tuple is recursively, as it was originally done in the Loki library. This will lay the fields out in reverse order (the most-base class, whose subobject comes first, is the leaf for the last member of the typelist). That's not the only possible implementation though, and I have observed the field order differing between compilers/standard library implementations.
NB. as mentioned in a comment, your current diagnostic has UB - however, you can hexdump the 4 bytes at reinterpret_cast<char*>(&i.z) safely and get an equivalent result.
|
69,767,789 | 69,775,621 | RichEdit doesn't show pictures | I created a simple RTF-document in WordPad, here is the screenshot:
It seems, that all format things of RTF work properly except pictures, which replaced by empty string. Here is RichEdit screenshot:
I tried both .bmp and .png. I also tried different version of RichEdit libraries: Riched20.dll and Msftedit.dll. Inside my .rtf file there is a string {\*\generator Riched20 10.0.19041}, I suppose it's a library and SDK version and in Visual Studio I use the same.
The code I use for loading RTF is popular and is taken from internet:
static DWORD CALLBACK FileStreamCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb)
{
std::ifstream* pFile = (std::ifstream*)dwCookie;
pFile->read((char*)pbBuff, cb);
return 0;
}
// ...
std::fstream file{ filePath };
EDITSTREAM editStream = { 0 };
editStream.dwCookie = (DWORD)&file;
editStream.pfnCallback = FileStreamCallback;
SendMessage(hwndEdit, EM_STREAMIN, SF_RTF, (LPARAM)&editStream);
And here is the RTF with cut image data for brevity:
{\rtf1\ansi\ansicpg1251\deff0\nouicompat\deflang1049\deflangfe1049{\fonttbl{\f0\fswiss\fprq2\fcharset204 Calibri;}{\f1\fswiss\fprq2\fcharset0 Calibri;}}
{\colortbl ;\red0\green0\blue255;}
{\*\generator Riched20 10.0.19041}{\*\mmathPr\mdispDef1\mwrapIndent1440 }\viewkind4\uc1
\pard\nowidctlpar\sa200\sl240\slmult1\f0\fs22{\pict{\*\picprop}\wmetafile8\picw1323\pich1323\picwgoal750\pichgoal750
010009000003260300000000fd02000000000400000003010800050000000b0200000000050000
// intermediate data
0000002701ffff030000000000
}\par
\strike Hello\strike0 .\par
\pard
{\pntext\f0 a.\tab}{\*\pn\pnlvlbody\pnf0\pnindent0\pnstart1\pnlcltr{\pntxta.}}
\nowidctlpar\fi-360\li720\sa200\sl240\slmult1\f1\lang1033 34\f0\lang1049\par
{\pntext\f0 b.\tab}\f1\lang1033 28\f0\lang1049\par
\pard\nowidctlpar\sa200\sl240\slmult1 {\f1\lang1033{\field{\*\fldinst{HYPERLINK www.google.com }}{\fldrslt{www.google.com\ul0\cf0}}}}\f0\fs22\par
}
Also I've found few allegations, that RichEdit is actually can't process images using the method described above. I don't know how to treat them.
| To insert a bitmap in to richedit, see this example (InsertObject(HWND hRichEdit, LPCTSTR pszFileName))
Otherwise, the bitmap in WordPad's rtf files is save as numbers in decimal format. To read that, IRichEditOleCallback interface is needed.
Create a new file called "cole_callback.h" as follows:
#include <richole.h>
interface cole_callback : public IRichEditOleCallback
{
public:
IStorage* pstorage;
DWORD m_ref;
int grfmode;
cole_callback() : grfmode(STGM_TRANSACTED | STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE)
{
pstorage = nullptr;
m_ref = 0;
(void)StgCreateDocfile(NULL, grfmode, 0, &pstorage);
}
HRESULT STDMETHODCALLTYPE GetNewStorage(LPSTORAGE* lplpstg)
{
wchar_t name[256] = { 0 };
return pstorage->CreateStorage(name, grfmode, 0, 0, lplpstg);
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** lplpObj)
{
*lplpObj = NULL;
if (iid == IID_IUnknown || iid == IID_IRichEditOleCallback)
{
*lplpObj = this;
AddRef();
return NOERROR;
}
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef()
{
return ++m_ref;
}
ULONG STDMETHODCALLTYPE Release()
{
if (--m_ref == 0) { delete this; return 0; }
return m_ref;
}
STDMETHOD(GetInPlaceContext) (LPOLEINPLACEFRAME FAR*, LPOLEINPLACEUIWINDOW FAR*, LPOLEINPLACEFRAMEINFO) { return S_OK; }
STDMETHOD(ShowContainerUI) (BOOL) { return S_OK; }
STDMETHOD(QueryInsertObject) (LPCLSID, LPSTORAGE, LONG) { return S_OK; }
STDMETHOD(DeleteObject) (LPOLEOBJECT) { return S_OK; }
STDMETHOD(QueryAcceptData) (LPDATAOBJECT, CLIPFORMAT FAR*, DWORD, BOOL, HGLOBAL) { return S_OK; }
STDMETHOD(ContextSensitiveHelp) (BOOL) { return S_OK; }
STDMETHOD(GetClipboardData) (CHARRANGE FAR*, DWORD, LPDATAOBJECT FAR*) { return S_OK; }
STDMETHOD(GetDragDropEffect) (BOOL, DWORD, LPDWORD) { return S_OK; }
STDMETHOD(GetContextMenu) (WORD, LPOLEOBJECT, CHARRANGE FAR*, HMENU FAR*) { return S_OK; }
};
Next step, create a new instance of cole_callback, and send it using EM_SETOLECALLBACK message. Follow by reading the rtf file using EM_STREAMIN
#include <"cole_callback.h">
...
LoadLibrary(L"Riched20.dll");
...
cole_callback* ole_callback = new cole_callback;
...
richedit = CreateWindowEx(0, RICHEDIT_CLASS, ...
SendMessage(richedit, EM_SETOLECALLBACK, 0, (LPARAM)ole_callback);
auto callback = [](DWORD ptr, LPBYTE buf, LONG count, LONG* red)
{
auto fp = (std::ifstream*)ptr;
fp->read((char*)buf, count);
*red = (LONG)fp->gcount();
return DWORD(0);
};
std::ifstream fin(L"c:/test/document.rtf", std::ios::binary);
EDITSTREAM es{ (DWORD_PTR)&fin, 0, callback };
SendMessage(richedit, EM_STREAMIN, WPARAM(SF_RTF), (LPARAM)&es);
|
69,768,913 | 69,771,855 | Does using different Boost versions affect serialization and deserialization? | I'm working on some project in C++ where I'm using Boost for binary serialization and deserialization. Serialization feature is already present with Boost version 1.61 I made my whole deserialization add on feature using Boost version 1.77 and now I'm facing problem while reading binary files. So, my question is how does this difference in version for deserialization affects the process? Because I'm unable to properly read the binary file.
Code using Boost version 1.61 for serialization
#include <boost/archive/binary_oarchive.hpp>
#include <fstream>
#include <string>
class Frame{
public:
std::string str;
};
template <typename Archive>
void serialize(Archive& ar, Frame& f, const unsigned int version) {
ar& f.str;
}
uint32_t main () {
Frame f={"Frame example"};
std::ofstream ofs;
ofs.open("BinaryFile.bin",std::ios::out, std::ios::binary);
boost::archive::text_oarchive write(ofs,boost::archive::no_header);
write << f;
ofs.close();
}
Code using boost version 1.77 for deserialization
#include <boost/archive/binary_iarchive.hpp>
#include <fstream>
#include <string>
class Frame{
public:
std::string str;
};
template <typename Archive>
void serialize(Archive& ar, Frame& f, const unsigned int version) {
ar& f.str;
}
uint32_t main () {
Frame f;
std::ofstream ofs;
ofs.open("BinaryFile.bin",std::ios::in, std::ios::binary);
boost::archive::text_oarchive read(ofs,boost::archive::no_header);
read >> f;
ofs.close();
}
This is just an example code the frame I am using is different but approach is same.
| There is backwards compatibility. But it requires the archive headers to be present so the library can detect the version support required for de-serialization.
Without the header, there's no way to tell, so the library must assume it's the most current version.
Removing that should work, see it live:
save in 1.61.0: https://wandbox.org/permlink/PkqDp4fWrno9GLql
read in 1.76.0: https://wandbox.org/permlink/PAwLOhVg0STNGN59
On my machine the read side worked with the same file in Boost 1.77.0 (not available on wandbox):
Success: Frame example
Summarizing
You should probably switch the file format to use the headers. This will probably require some kind of conversion tool. If all else fails you might opt to distinguish the versions by their filename/extension. That's brittle, but if it's the only thing you can control it might save you.
|
69,769,335 | 69,850,267 | Targetting Windows 8.1 with Windows 10 SDK in C++ | we currently build our C++ Code with Visual Studio 2017 and we were required to have our binaries run on Windows 7 as well until only recently.
Hence our settings in C++ projects for the Windows SDK version to be used is "8.1" and by defining _WIN32_WINNT=0x601 as a preprocessor macro, we target Windows 7 as a platform, as recommended at various places by Microsoft.
Now we want to add ARM64 as a new platform, but this requires the Windows SDK version to be set to 10.0.10240.0 and since the Windows SDK Version to be used is a project global setting, this would affect the existing other platforms we build for (Win32 and x64) as well.
Now if we set the Windows SDK version from 8.1 to 10.0.10240.0 (or later versions), would we lose the ability to run our code on Windows 8.1, as long as we use _WIN32_WINNT=0x602 (for targetting Windows 8.1)?
| The comment from Minxin Yu is the answer to this question. This discussion
points to the Windows SDK page that clearly states that the current Win10 SDK allows for targetting Windows 7 SP1 and Windows 8.1.
|
69,769,487 | 69,770,632 | c++ replace values in linked list by changing pointers | Having a problem with linked list. Need to create a method, which will replace data in list, by not creating a new element but by changing pointers. For now I have such method:
void replaceValues(Node* head, int indexOne, int indexTwo)
{
Node* temporaryOne = NULL;
Node* temporaryTwo = NULL;
Node* temp = NULL;
Node* current = head;
int count = 0;
while (current != NULL) {
if (count == indexOne)
{
temporaryOne = current;
}
else if (count == indexTwo)
{
temporaryTwo = current;
}
count++;
current = current->next;
}
current = head;
count = 0;
while (current != NULL) {
if (count == indexOne)
{
head = temporaryTwo;
}
else if (count == indexTwo)
{
head = temporaryOne;
}
count++;
current = current->next;
}
}
I am sure, that exists a more simpler way, how to do it, but I don't fully understand, how it works...
Thanks in advance for help.
| I assume that with "replace" you actually mean "swap"/"exchange".
Some issues:
The argument head should be passed by reference, as one of the nodes to swap may actually be that head node, and then head should refer to the other node after the function has done its job.
The node before temporaryOne will need its next pointer to change, so you should stop your loops one step earlier in order to have access to that node and do that.
In some cases head may need to change, but this is certainly not always the case, so doing head = temporaryOne or head = temporaryTwo is certainly not right. In most cases you'll need to link to the swapped node from the preceding node (see previous point).
The next pointer of the node that is swapped will also need to change, as the node that follows it will be a different one than before.
As mentioned already in comments, it is advised to split the task into removals and insertions, as the fiddling with next pointers can get confusing when you try to cover all possible cases, notably making the distinction between the case where the two nodes are adjacent and when they are not.
Here are some functions that split the work into removal, insertion and finally exchanging nodes:
Node* removeNode(Node* &head, int index) {
// If index is out of range, no node is removed, and function returns nullptr
// Otherwise the extracted node is returned.
if (head == nullptr || index < 0) return nullptr;
Node* current = head;
if (index == 0) {
head = head->next;
current->next = nullptr;
return current;
}
while (--index > 0) {
current = current->next;
if (current == nullptr) return nullptr;
}
Node* temp = current->next;
if (temp != nullptr) {
current->next = temp->next;
temp->next = nullptr;
}
return temp;
}
void insertNode(Node* &head, Node* node, int index) {
// If index is too large, node is inserted at the end of the list
// If index is negative, node is inserted at the head of the list
if (index <= 0 || head == nullptr) {
node->next = head;
head = node;
return;
}
Node* current = head;
while (--index > 0 && current->next != nullptr) {
current = current->next;
}
node->next = current->next;
current->next = node;
}
bool exchangeNodes(Node* &head, int indexOne, int indexTwo)
{
// Returns true when successful, false when at least one index
// was out of range, or the two indexes were the same
if (head == NULL || head->next == NULL || indexOne == indexTwo || indexOne < 0) return false;
// To ensure the right order of operations, require the first index is the lesser:
if (indexOne > indexTwo) return exchangeNodes(head, indexTwo, indexOne);
Node* two = removeNode(head, indexTwo);
if (two == nullptr) return false; // out of range
Node* one = removeNode(head, indexOne);
insertNode(head, two, indexOne);
insertNode(head, one, indexTwo);
return true;
}
|
69,769,489 | 69,769,674 | C++: read int from binaryfile | I have pixels from an image which are stored in a binary file.
I would like to use a function to quickly read this file.
For the moment I have this:
std::vector<int> _data;
std::ifstream file(_rgbFile.string(), std::ios_base::binary);
while (!file.eof())
{
char singleByte[1];
file.read(singleByte, 1);
int b = singleByte[0];
_data.push_back(b);
}
std::cout << "end" << std::endl;
file.close();
But on 4096 * 4096 * 3 images it already takes a little time.
Is it possible to optimize this function?
| You could make this faster by reading the whole file in one go, and preallocating the necessary storage in the vector beforehand:
std::ifstream file(_rgbFile.string(), std::ios_base::binary);
std::streampos posStart = file.tellg();
file.seekg(0, std::ios::end);
std::streampos posEnd = file.tellg();
file.seekg(posStart);
std::vector<char> _data;
_data.resize(posEnd - posStart, 0);
file.read(&_data[0], posEnd - posStart);
std::cout << "end" << std::endl;
file.close();
Avoiding unnecessary i/o
By reading the file as a whole in one read() call you can avoid a lot of read calls, and buffering of the ifstream. If the file is very large and you don't want to load it all in memory at once, then you can load smaller chunks of maybe a few MB each.
Also you avoid lots of functions calls - by reading it byte-by-byte you need to issue ifstream::read 50'331'648 times!
vector preallocation
std::vector grows dynamically when you try to insert new elements but no space is left. Each time the vector resizes, it needs to allocate a new, larger, memory area and copy all current elements in the vector over to the new location.
Most vector implementions choose a growth factor between 1.5 - 2, so each time the vector needs to resize it'll be a 1.5-2x larger allocation.
This can be completely avoided by calling std::vector::reserve or std::vector::resize.
With these functions the vector memory only needs to be allocated once, with at least as many elements as you requested.
Godbolt example
Here's a godbolt example that shows the performance improvement.
testing a ~5MB file (4096*4096*3 bytes)
gcc 11.2, with optimizations disabled:
Old
New
1300ms
16ms
gcc 11.2, -O3
Old
New
878ms
13ms
Small bug in the code
As @TedLyngmo has pointed out your code also contains a small bug.
The EOF marker will only be set once you tried to read past the end of the file. see this question
So the last read that sets the EOF bit didn't actually read a byte, so you have one more byte in your array that contains uninitialized garbage.
You could fix this by checking for EOF directly after the read:
while(true) {
char singleByte[1];
file.read(singleByte, 1);
if(file.eof()) break;
int b = singleByte[0];
_data.push_back(b);
}
|
69,769,633 | 69,771,522 | C++ Sorting Algorithm Returns in the Quintillions When Given 0 | I'm trying to write my first sorting algorithm in C++, I'm relatively new to it so this might be an endeavor beyond me but I thought I could handle it. When given the input 0 this code returns numbers such as 701635989630, 6560204700, and 1.8*10^19. This doesn't make sense to me at all, nor the people I have asked IRL.
Edit - @Slava had the best suggestion and with his help I was able to get it to work 4 out of 5 times now, but it still fails on the 5th
#include <cinttypes>
uint64_t descendingOrder(uint64_t a)
{
std::vector<int> digits;
for( auto tmp = a; tmp; tmp /= 10 ){
digits.push_back( tmp % 10 );
}
bool run = true;
//sort the array
while (run) {
bool change = false;
for (unsigned long z = 1; z < std::size(digits); ++z){
if (digits[z]>digits[z-1]){
unsigned long temp = digits[z];
digits[z] = digits[z-1];
digits[z-1] = temp;
change = true;
};
};
if (change == false){
run = false;
};
};
int finSort = 0;
for (unsigned long i = 0; i < std::size(digits); i++) {
finSort *= 10;
finSort += digits[i];
}
return finSort;
}
|
C++ Sorting Algorithm Returns in the Quintillions When Given 0
Sorting algorithms sort things. They don't, as a rule, return integers.
uint64_t descendingOrder(uint64_t a)
This is a function that does three things:
convert an integer into an array of digits
sort the array of digits
convert the sorted array of digits back into an integer
That's two things too many, and only one of them is really relevant to the question. It's clearly not a minimal reproducible example because the bug is in your sorting code, not in your integer-digit-array-conversion code.
Let's rewrite the function so it isn't trying to do too many things:
uint64_t descendingOrder(uint64_t a)
{
auto digits = integer_to_digits(a);
bubble_sort(digits);
return digits_to_integer(digits);
}
You already have working code for integer_to_digits and digits_to_integer so I'm not going to write them out - and anyway, they don't belong in your question in the first place.
Now, we can write the minimal code needed to demonstrate the problem, starting with your existing sorting code:
void bubble_sort(std::vector<int> &digits)
{
bool run = true;
while (run) {
bool change = false;
for (unsigned long z = 1; z < digits.size(); ++z){
if (digits[z]>digits[z-1]){
unsigned long temp = digits[z];
digits[z] = digits[z-1];
digits[z-1] = temp;
change = true;
}
}
if (change == false){
run = false;
}
}
}
and a trivial test harness so we can see it working:
void test_bubble_sort(std::vector<int> &digits)
{
std::cout << "{";
std::copy(digits.begin(), digits.end(), std::ostream_iterator<int>(std::cout, ","));
std::cout << "} -> {";
bubble_sort(digits);
std::copy(digits.begin(), digits.end(), std::ostream_iterator<int>(std::cout, ","));
std::cout << "}\n";
}
int main() {
std::vector<int> empty;
test_bubble_sort(empty);
std::vector<int> zero{0};
test_bubble_sort(zero);
std::vector<int> one{1};
test_bubble_sort(one);
std::vector<int> inc{1, 2, 3};
test_bubble_sort(inc);
std::vector<int> dec{3, 2, 1};
test_bubble_sort(dec);
}
... and the sort itself seems to be fine.
If you have a problem in reality with the integer_to_digits or digits_to_integer, write another test for those, and if necessary ask a question specific to them. Neither the test harness nor the question will have any bubble sorting in them, because these problems are completely unrelated.
When you have a working, tested bubble sort and working, tested integer-digit-array conversion, then you can combine them into a program that does two things.
|
69,769,750 | 69,769,879 | How can I determine, if a templated class is a sublass of another templated class, as the templates might differ? | Consider the following class structure:
template <typename TType>
struct Base {public: virtual ~Base() {} };
template <typename TType>
struct Child : Base<TType> {};
template <template<typename> class Node, typename TType>
bool type(Node <TType>* node){
return dynamic_cast<Base<TType>*>(node) == nullptr;
}
int main(){
Child<int> child;
type(&child);
}
This code works fine, as long as the child has the same template type before and after casting. If this is not the case, it will of course fail. If they have different types and I provide the specific type of the inherited template, it will work, but I have a very big number of possible templates. My first instinct was to add another template:
template <template<typename TType> class Node, typename TType, typename TType2>
bool type(Node <TType>* node){
return dynamic_cast<Base<TType2>*>(node) == nullptr;
}
This will give an error "couldn't deduce template parameter", because the compiler does not know which type it is, as no corresponding parameter is passed (but I am not able to provide this in beforehand).
Is there any solution to this? I am also open to other possibilites than dynamic_cast, as my actual goal is, if the templated node is a subclass of the also templated baseclass.
I tried e.g. is_base_of without success. Something around the lines of is_base_of<Base, typeid(child)>::value did not work because of a type msimatch in the arguments.
| You might use overload:
template <typename T>
constexpr std::true_type IsBaseT(const Base<T>*) { return {}; }
constexpr std::false_type IsBaseT(const void*) { return {}; }
Demo
That assumes accessible, non ambiguous base. And result is based on static type.
So you can turn that into a traits:
template <typename T>
std::true_type IsBaseTImpl(const Base<T>*); // No impl
std::false_type IsBaseTImpl(const void*); // No impl
template <typename T>
using IsBaseT = decltype(IsBaseTImpl(std::declval<T*>()));
And a more generic form:
template <template <typname> C, typename T>
std::true_type IsCTImpl(const C<T>*); // No impl
template <template <typname> C>
std::false_type IsCTImpl(const void*); // No impl
template <template <typname> C, typename T>
using IsCT = decltype(IsCTImpl<C>(std::declval<T*>()));
template <typename T>
using IsBaseT = IsCT<Base, T>;
|
69,769,815 | 69,769,950 | How XOR Assignment operator ^= is utilized to reverse an array in c | i encountered to this function
void reverseArray(int *a,int n)
{
for(int i=0,j=n-1;i<j;i++,j--)
{
a[i]^=a[j]^=a[i]^=a[j];
}
}
which is reversing a given array but I can't wrap my mind around how does this reverse an array, isn't Xor operator only returns the non-common bits.
so what's the logic behind this to reverse the given array.
| The purpose of the expression a^=b^=a^=b is to exchange the values of a and b. It becomes more clear if we split it up (where a_0 and b_0 are the original values of a and b):
First assignment, a^=b makes a_1=(a_0^b_0).
Second assignment, b^=a makes b_1=(b_0^a_1)=(b_0^(a_0^b_0))=a_0
Third assignment, a^=b makes a_2=(a_1^b_1)=((a_0^b_0)^a_0)=b_0
Thus we end up with a having the original value of b and vice versa.
While the expression a^=b^=a^=b may work it is actually undefined behavior because the C standard does not specify the order of assignments. Instead, it must be sequenced explicitly: a^=b; b^=a; a^=b;.
|
69,770,000 | 69,781,346 | Count of binary numbers from 1 to n | I want to find the number of numbers between 1 and n that are valid numbers in base two (binary).
1 ≤ n ≤ 10^9
For example, suppose n is equal to 101.
Input: n = 101
In this case, the answer is 5
Output: 1, 10, 11, 100, 101 -> 5
Another example
Input: n = 13
Output: 1, 10, 11 -> 3
Here is my code...
#include <iostream>
using namespace std;
int main()
{
int n, c = 0;
cin >> n;
for (int i = 1; i <= n; ++i)
{
int temp = i;
bool flag = true;
while(temp != 0) {
int rem = temp % 10;
if (rem > 1)
{
flag = false;
break;
}
temp /= 10;
}
if (flag)
{
c++;
}
}
cout << c;
return 0;
}
But I want more speed.
(With only one loop or maybe without any loop)
Thanks in advance!
| Details:
In each step, if the digit was one, then we add 2 to the power of the number of digits we have.
If the number was greater than 1, then all cases are possible for that number of digits, and we can also count that digit itself and change the answer altogether (-1 is because we do not want to calculate the 0).
#include <iostream>
using namespace std;
int main()
{
long long int n, res = 0, power = 1;
cin >> n;
while(n != 0) {
int rem = n % 10;
if (rem == 1) {
res += power;
} else if (rem > 1) {
res = 2 * power - 1;
}
n /= 10;
power *= 2;
}
cout << res;
return 0;
}
|
69,770,785 | 69,770,898 | How to cycle through smart pointer to a class with custom iterator | I have a smart pointer to a class with custom iterator. I need to iterate through it and couldn't find any examples.
struct SomeContrainer
{
int a;
}
struct ListClass
{
std::vector<SomeContrainer>::iterator begin() { return m_devs.begin(); }
std::vector<SomeContrainer>::iterator end() { return m_devs.end(); }
void add( const SomeContrainer& dev ) { m_devs.push_back( dev ); }
private:
std::vector<SomeContrainer> m_devs;
};
typedef std::unique_ptr<ListClass> ListPtr_t;
void Foo_Add( const ListPtr_t& list )
{
SomeContrainer dev1, dev2;
dev1.a = 10;
dev2.a = 100;
list->add(dev1);
list->add(dev2);
}
void DoSomeWorkOtherList( const ListPtr_t& list )
{
for( auto const& dev : list ) // <-- how to iterate over list ???
{}
}
// -----------
ListPtr_t pMyList( new ListClass() );
Foo_Add( pMyList );
DoSomeWorkOtherList(pMyList );
It works fine if I don't use a smart pointer and have just an object ListClass list I'm using C++11 and can't upgrade.
| you need to dereference it
void DoSomeWorkOtherList( const ListPtr_t& list ) // void(const unique_ptr<ListClass>&)
{
for( auto const & dev : *list ) // <-- how to iterate other list ???
{}
}
Not necessary for the code in question, but you probably also want to provide const version of begin and end.
std::vector<SomeContrainer>::const_iterator begin() const { return m_devs.begin(); }
std::vector<SomeContrainer>::const_iterator end() const { return m_devs.end(); }
|
69,770,834 | 69,770,999 | Is it possible to call Class member constructor inside class constructor? | I would like to be able to initialize a class member in one of N ways (in this examples N=2) based on a condition that is recieved via the class constructor as in the code that follows, but the MainObject's initialization seems to be only local to the (container) class' constructor. I wonder what are the best-practices for this particular pattern.
// in ContainerObject.hpp
class ContainerObject {
public:
MainClass MainObject;
ContainerObject(int type);
}
// in ContainerObject.cpp
ContainerObject::ContainerObject(int type);{
if (type == 0){
MainObject("something", 1, 2);
} else if (type == 1){
MainObject(4, "another thing", "yet another thing");
}
}
I have so-far thought about
putting the main object in the heap
defining N class constructors and call the appropiate one recursively inside the "main"/"first" class constructor.
please note that the "0" and "1" initialization is only an example and it could be drastically different.
EDIT1: added ";" required for compiling
EDIT2:
Changed the original
//...
if (type == 0){
MainObject(0);
} else if (type == 1){
MainObject(1);
}
//...
for the current one
//...
if (type == 0){
MainObject("something", 1, 2);
} else if (type == 1){
MainObject(4, "another thing", "yet another thing");
}
//...
as it was called a duplicate by being misinterpreted for a case that could be solved by adding the following.
//...
ContainerObject(int type): MainObject(type);
//...
| I am interpreting the question as "how to perform non-trivial logic before/during the member initialization list".
A good way to go about that is to delegate the work of converting the constructor parameter of the outer object into the child object to a utility function:
// in ContainerObject.cpp
#include <stdexcept> // for std::invalid_argument
// Anonymous namespace since main_factory() is only needed in this TU.
namespace {
MainClass main_factory(int type) {
if (type == 0) {
return MainClass("something", 1, 2);
} else if (type == 1) {
return MainClass(4, "another thing", "yet another thing");
}
// N.B. This is one of the scenarios where exceptions are indisputably
// the best way to do error handling.
throw std::invalid_argument("invalid type for MainClass");
}
}
ContainerObject::ContainerObject(int type)
: MainObject(main_factory(type)) {}
|
69,770,854 | 69,772,106 | Redefining a handle ptr of void* to handle ptr to struct* (C/C++ mixcode) for access | I have C/C++ mix code and want to pass around a struct that contains a reference to a class. Because of this, I can't declare this struct in the header file of the C++ component (because class is defined in source file of C++ component) but only in the source file. The main script in C however has to reference that struct somehow, so I typedef it to void*. However because of that, I can't dereference the handle type back to a struct. Redefining the handle pointer in the source file is not possible. How can I work around this?
header_with_obj.hpp
class A {
int a;
};
header.hpp
typedef void* config_handle_t;
source.cpp
#include "header.hpp"
#include "header_with_obj.hpp"
typedef struct {
A* ptr;
int some_other;
} config_t;
// typedef config_t* config_handle_t <-- error: conflicting declaration 'typedef struct config_t* config_handle_t '
int foo(void* arg)
{
config_handle_t handle = (config_handle_t) arg;
handle->A.a = 4; // <-- error: 'config_handle_t' {aka 'void*'} is not a pointer-to-object type
}
main.c
#include "header.hpp"
int main()
{
// we get that void* from somewhere and pass it in
foo(arg);
}
| The usual way to do this is to use an undefined struct. In its most basic form:
void foo(struct the_config_struct *arg);
// OK even though 'struct the_config_struct' wasn't defined!
// surprisingly this is also allowed in C++
You can also make a typedef:
typedef struct the_config_struct *config_handle_t;
void foo(config_handle_t arg);
and if you want, you can even call the typedef the same thing as the struct. Just to avoid confusing people, I wouldn't do this unless it's a typedef for the struct (not a pointer).
typedef struct the_config_struct the_config_struct;
void foo(the_config_struct *arg);
You don't to actually have defined the struct until you want to access its members:
// if we uncomment this definition then it's OK
// struct my_struct {
// char *message;
// };
void foo(struct my_struct *arg) {
puts(arg->message); // error: struct my_struct is undefined
}
Finally (since this confused you before) you should know that typedef names and struct names are completely separate in C.
struct foo {}; // defines "struct foo" but "foo" is completely unrelated
typedef int bar; // defines "bar" but "struct bar" is completely unrelated
foo *get_foo(); // error: "foo" is unknown
struct foo *get_foo(); // OK
typedef struct bar foo;
foo *get_bar(); // OK: returns pointer to struct bar (not struct foo!)
struct foo *get_foo(); // this one returns pointer to struct foo
struct baz {};
typedef struct baz baz;
// now "baz" is an alternative name for "struct baz" - they are interchangeable
typedef struct baz {} baz; // short version
and structs don't have to have names:
// foo is a variable, and it's a struct variable, but the struct has no name.
// so we have no way to use the struct for anything else.
struct {
int i;
} foo;
// The struct is still there even though it doesn't have a name!
// In C++ you can write decltype(bar) to say "the same type as variable bar".
// Even though we don't know the person's name we can still yell out "Hey you in the red shirt!"
decltype(foo) foo2; // a variable foo2. The type is decltype(foo) i.e. the struct from before
// GCC lets you do it in C using "typeof".
// This is not standard. It's a special feature in GCC.
typeof(foo) foo2;
// This struct also has no name either. But the typedef means we have
// an "unofficial" way to name it, just like decltype(foo) before.
// This is valid in C as well as C++.
typedef struct {
char message[50];
} bar;
|
69,771,109 | 69,771,250 | C++ Reverse Array of std::vector of two elements | I would like to ask how can I fastly, without copying of elements reverse the array, that will always consists only from 2 std::vectors. The CGAL_Polyline is also a vector that contains points.
Currently I am doing reverse like this (works for now but I do not know if this is a correct way):
std::vector<CGAL_Polyline> m[2]; //array to reverse
std::vector<CGAL_Polyline> m_[2]{ m[1], m[0] };
m[0] = m_[0];
m[1] = m_[1];
this does not work, why?
std::vector<CGAL_Polyline> m[2]; //array to reverse
std::reverse(m.begin(), m.end());
Is there any other way to flip the order of two vectors? I do not need to reverse order of items in the vectors.
| Use std::swap:
std::vector<CGAL_Polyline> m[2];
...
std::swap(m[0], m[1]);
This will move the contents of the vectors without copying (C++11 and later. Before that it's allowed to copy).
If pre-C++11 (and if that's the case upgrade your compiler!) you can use std::vector::swap:
std::vector<CGAL_Polyline> m[2];
...
m[0].swap(m[1]);
Since it's guaranteed to be constant.
|
69,771,112 | 69,771,644 | Factory for a template class with enum template parameter | Suppose I have
enum class Colour
{
red,
blue,
orange
};
class PencilBase
{
public:
virtual void paint() = 0;
};
template <Colour c>
class Pencil : public PencilBase
{
void paint() override
{
// use c
}
};
Now I want to have some factory function to create painters
PencilBase* createColourPencil(Colour c);
What will be the most elegant way to implement this function?
I want to avoid making changes in this function (or its helpers) when I decide to introduce a new colour.
I feel like we have all the information at compile time to achieve this, however I am having trouble to find a solution.
| Firstly, you need to know how many colors are there:
enum class Colour
{
red,
blue,
orange,
_count, // <--
};
After you know the number, you can create an array of function pointers of this size, each function creating the respective class. Then you use the enum as an index into the array, and call the function.
std::unique_ptr<PencilBase> createColourPencil(Colour c)
{
if (c < Colour{} || c >= Colour::_count)
throw std::runtime_error("Invalid color enum.");
static constexpr auto funcs = []<std::size_t ...I>(std::index_sequence<I...>)
{
return std::array{+[]() -> std::unique_ptr<PencilBase>
{
return std::make_unique<Pencil<Colour(I)>>();
}...};
}(std::make_index_sequence<std::size_t(Colour::_count)>{});
return funcs[std::size_t(c)]();
}
Template lambas require C++20. If you replace the outer lambda with a function, it should work in C++17 as well.
MSVC doesn't like the inner lambda, so if you're using it, you might need to convert it to a function too. (GCC and Clang have no problem with it.)
I've used unique_ptr here, but nothing stops you from using the raw pointers.
gcc 7.3.1 is not able to handle this code
Here it is, ported to GCC 7.3:
template <Colour I>
std::unique_ptr<PencilBase> pencilFactoryFunc()
{
return std::make_unique<Pencil<I>>();
}
template <std::size_t ...I>
constexpr auto makePencilFactoryFuncs(std::index_sequence<I...>)
{
return std::array{pencilFactoryFunc<Colour(I)>...};
}
std::unique_ptr<PencilBase> createColourPencil(Colour c)
{
if (c < Colour{} || c >= Colour::_count)
throw std::runtime_error("Invalid color enum.");
static constexpr auto funcs = makePencilFactoryFuncs(std::make_index_sequence<std::size_t(Colour::_count)>{});
return funcs[std::size_t(c)]();
}
|
69,771,416 | 69,771,502 | Is it safe to cast a class to a derived class that just adds additional functions? | I have a class that contains a lot a data. Depending on the situation I need to output this data in different ways. I want the output routines for each of those situations separated and I want to keep the base class clean of that.
Is it absolutely safe to cast to a derived class that does NOT add any data members but just non-virtual functions?
#include <stdio.h>
class Base {
public:
Base() { printf("Base()\n"); }
double A = 3.14;
int B = 5;
int C = 42;
};
class Derived1 : public Base {
public:
Derived1() { printf("Derived1()\n"); }
void DoStuff() {
// doing stuff with base class's data
printf(" A = %.4f\n", A);
printf(" B = %d\n", B);
printf(" C = %d\n", C);
}
};
class Derived2 : public Base {
public:
Derived2() { printf("Derived2()\n"); }
void DoStuff() {
// doing stuff with base class's data in a slightly different way
printf(" A = %.4f, B = %d, C = %d\n", A, B, C);
}
};
class OtherBase {
public:
OtherBase() { printf("OtherBase()\n"); }
int D = 10;
};
class Derived3 : virtual public OtherBase, virtual public Base {
public:
Derived3() { printf("Derived3()\n"); }
void SomeFunction() {
A = 6.28;
B = 1;
C = 500;
printf("Done some other stuff.\n");
}
};
int main() {
printf("Base class\n\n");
Base* Instance = new Base();
printf("Cast to Derived1:\n");
static_cast<Derived1*>(Instance)->DoStuff();
printf("Cast to Derived2:\n");
static_cast<Derived2*>(Instance)->DoStuff();
printf("\nOther class derived from base class\n\n");
Derived3* Instance2 = new Derived3();
Instance2->SomeFunction();
printf("Cast to Derived1:\n");
static_cast<Derived1*>(static_cast<Base*>(Instance2))->DoStuff();
printf("Cast to Derived2:\n");
static_cast<Derived2*>(static_cast<Base*>(Instance2))->DoStuff();
printf("c-style cast to Derived1:\n");
((Derived1*) Instance2)->DoStuff();
printf("c-style cast to Derived2:\n");
((Derived2*) Instance2)->DoStuff();
return 0;
}
The part where class "Derived3" (that has virtual inheritance of "Base") is cast to "Base" first and then to "Derived1"/"Derived2" does not look very good to me but I know how c-style casts are frowned upon in the c++ community. In this small example however, the c-style cast are compiling and working nicely:
I know there is the issue with multiple inheritance where a cast to one of the base classes can have a different pointer address then the inherited class it was cast from. So I understand that it might be too dangerous to rely on it.
Are the static casts I did in the example at the top safe?
| No, this isn't safe. The behaviour of the program is undefined.
Static casting to a derived type is safe only when the dynamic type of the object is that derived type (or a further derived type).
|
69,771,634 | 69,772,235 | IEEE 754 Addition of two 32-bit floating point numbers (-1 and 2^(-50) ) | Consider the following piece of C++ Code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout.precision(1000000000);
float a,b,c;
a = 1;
b = -1;
c = pow(2, -50);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
float ab = a + b;
float bc = b + c;
float abc = ab + c;
float bca = bc + a;
cout << "a + b = " << ab << endl;
cout << "b + c = " << bc << endl;
cout << "(a + b) + c = " << abc << endl;
cout << "(b + c) + a = " << bca << endl;
return 0;
}
Which yields the output:
a = 1
b = -1
c = 8.8817841970012523233890533447265625e-16
a + b = 0
b + c = -1
(a + b) + c = 8.8817841970012523233890533447265625e-16
(b + c) + a = 0
Why is b + c = -1?
I am not getting my head around this effect of the IEEE 754 standard.
To my understanding the exponent ranges from -126 to 127. (8 bit for the biased exponent with a bias of 127.)
So 2^(-50) is representable without an issue as is 1 or -1. Neither of them are subnormal (denormalized) numbers, if I understand the standard correctly.
But why does the addition of -1 + 2^(-50) result in -1, thus the smaller number being neglected?
Thanks in advance for any help!
| The IEEE 754 standard specifies 1 sign bit, 7 exponent bits and 24 bits for the mantissa. When performing addition, the mantissas of each number get normalized, so 2^-50 is 1 shifted right by 50 bits relative to 1. This causes it to fall outside of the 24 bit mantissa used for the result. You should try repeating your experiment with 2^-25 to prove this.
|
69,771,907 | 69,775,848 | c++ create a global unique id that is not a UUID type | In other languages, such as Go, there are a myriad of libraries that can be used to create a globally unique ID string (using elements such as nanosecond time, machine id, process id, random bytes...)
However, in C++, the only real choice seems to be UUID (such as that from Boost)
I am looking to use a globally unique identifier in my code, but do not want something with as many chars as a UUID.
As an example of the type of things available in GoLang. Please see the below. Anything similiar in c++?
https://blog.kowalczyk.info/article/JyRZ/generating-good-unique-ids-in-go.html
|
Please note that when I say "as many chars", I am referring to the string representation of a UUID
So, perhaps use your own representation.
You didn't specify a whole lot. Keep in mind that time-clustering might lead to security vulnerabilities¹. I'd assume UUIDv4 standard, meaning 16 bytes. Let's use the encoding from the linked page that looks shortish:
Live On Coliru
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <cstring>
#include <iostream>
#include <string_view>
using boost::uuids::uuid;
static_assert(uuid::static_size() == 16);
static constexpr auto alphabet57 =
"23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
std::string encode57(uuid uid) {
boost::uint128_type num;
std::reverse(uid.data, uid.data+16);
std::memcpy(&num, uid.data, 16);
std::string s;
s.reserve(12);
while (num) {
s += alphabet57[num % 57];
num /= 57;
}
return s;
}
uuid decode57(std::string_view s) {
boost::uint128_type num = 0;
for (auto it = s.rbegin(); it != s.rend(); ++it) {
num *= 57;
num += std::find(alphabet57, alphabet57 + 57, *it) - alphabet57;
}
uuid uid;
std::memcpy(uid.data, &num, 16);
std::reverse(uid.data, uid.data + 16);
return uid;
}
int main() {
for (std::string test : {
"f7dd5274-f457-4239-a881-801662d589ad", // sfitJnfge8vaXnga8kzi7n
"3b387615-24ed-4c17-a715-c4413ffac3b5", // Vq6uZe6usvSwWftVdBPbYC
"3dd64dba-1ff3-40e5-84e3-3fbb0f8b86b9", // r5D3drtfrx7322ajzYv82D
"b17a848e-5d6b-45d9-ae25-57cfb8a8fec3", // petYHah9W3p8GptQ9QJuaZ
"a9edc682-147c-4e41-85e2-e06c4ce64086", // DFLa6tquGSZvSEi2WE3MFY
"2cc90c4a-192f-4b57-bc11-2c322dab2ce0", // yyg6AekktrpjdBCjGjsCy9
"ac1d94bd-3fbc-46c1-aeec-cdcdc2dd0dd2", // dzHCNTADG6R4n3QTjm7XdY
"1e3df271-a3c2-4b45-8871-0fde4c2d97e8", // tL66L6gqRESaABWsxbrhP7
"0d15c1d5-3646-474f-8a5d-989878f12a95", // FtnvH2QRENpsFcLXq5zhL4
"ececc5dc-cdf1-49f4-b3f7-bfe8697133fd", // Dkfm7JmgVAuP28JLPDBnAk
}) //
{
auto const uid = boost::lexical_cast<uuid>(test);
auto const txt = encode57(uid);
std::cout << uid << " ~ " << txt << "\n";
assert(decode57(txt) == uid);
}
}
Prints
f7dd5274-f457-4239-a881-801662d589ad ~ sfitJnfge8vaXnga8kzi7n
3b387615-24ed-4c17-a715-c4413ffac3b5 ~ Vq6uZe6usvSwWftVdBPbYC
3dd64dba-1ff3-40e5-84e3-3fbb0f8b86b9 ~ r5D3drtfrx7322ajzYv82D
b17a848e-5d6b-45d9-ae25-57cfb8a8fec3 ~ petYHah9W3p8GptQ9QJuaZ
a9edc682-147c-4e41-85e2-e06c4ce64086 ~ DFLa6tquGSZvSEi2WE3MFY
2cc90c4a-192f-4b57-bc11-2c322dab2ce0 ~ yyg6AekktrpjdBCjGjsCy9
ac1d94bd-3fbc-46c1-aeec-cdcdc2dd0dd2 ~ dzHCNTADG6R4n3QTjm7XdY
1e3df271-a3c2-4b45-8871-0fde4c2d97e8 ~ tL66L6gqRESaABWsxbrhP7
0d15c1d5-3646-474f-8a5d-989878f12a95 ~ FtnvH2QRENpsFcLXq5zhL4
ececc5dc-cdf1-49f4-b3f7-bfe8697133fd ~ Dkfm7JmgVAuP28JLPDBnAk
¹ these all are examples of RFC4122 random-number based UUIDs, the default when using goolge/uuid in Go
These encodings have been verified with the ones generated by shortuuid
|
69,772,243 | 69,773,170 | How i can get all substring of size k of string? | I don't know where is the error in my code ? can someone help me to fix it .
My code :
#include<bits/stdc++.h>
using namespace std;
#define ll long long
void solution() {
string s;
ll k;
cin >> s >> k;
for(int i=0; i<=s.length()-k; i++) {
for(int r=k-1; r<s.length(); r++){
cout << s.substr(i,r) << endl;
}
}
}
int main() {
ll t;
cin >> t;
while(t--){
solution();
}
return 0;
}
input :
1
ABCD 3
Expected output:
ABC
BCD
Actual output:
AB
ABC
BC
BCD
| I have no idea why you need a nested for loop. Why isn't this just simply:
void solution() {
string s;
ll k;
cin >> s >> k;
for(int i = 0; i <= s.length() - k; i++) {
cout << s.substr(i, k) << endl;
}
}
|
69,772,513 | 69,772,650 | C++ what happens when 0 is assigned to class variable in constructor | I'm trying to create a smart pointer and stumbled over the code below. Since I'm pretty new to C++, its syntax is yet something I have to get used to.
Below you can see the most important part of the code where RC is the reference counter class with a member variable called count (of type int). The function addRef increments count with 1.
template < typename T > class SP
{
private:
T* pData; // pointer
RC* reference; // Reference count
public:
SP() : pData(0), reference(0)
{
reference = new RC();
reference->AddRef(); // Increment the reference count
}
//...
}
Now, what exactly happens when the constructor assigns 0 to pData and reference?
Further, is there a reason why a "default parameter" was omitted here? Something like this:
SP() : pData(0), reference(new RC())
| For historical reasons, 0 is equivalent to nullptr, which means "a pointer that does not point to anything". In modern code, you should always use nullptr, never 0.
Is this the way to go or are there "better" best practices?
Putting aside concerns about what is being executed, the most idiomatic way to write the same functionality as presented in the question is:
Use nullptr to express that a pointer points to nothing.
Use member initializers for default member values.
Use initializer lists to specify member initial values in place of the default when it differs.
Bonus: Always match your news with deletes, even in sample code.
template < typename T > class SP
{
private:
T* pData = nullptr;
RC* reference = nullptr;
public:
SP() : reference(new RC())
{
reference->AddRef();
}
SP(const SP&) = delete;
SP& operator=(const SP&) = delete;
~SP() {
delete reference;
}
//...
}
|
69,772,624 | 69,773,221 | Next higher number with same number of set bits and some bits fixed | I'm trying to find a way to, given a number of bits that need to be set, and a few indexes of bits that should remain fixed, generate the next higher number with the same number of set bits, that has all the fixed bits in place. This is closely related to https://www.chessprogramming.org/Traversing_Subsets_of_a_Set#Snoobing_the_Universe
The difference is that I want to keep some of the bits unchanged, and I'm trying to do this as efficiently as possible / something close to the snoob function, that given a number and the conditions, bithacks its way into the next one (So I'm trying to avoid iterating through all the smaller subsets and seeing which ones contain the required bits, for example).
For example, if I have the universe of numbers {1,2,...,20}, I'd like to, given a number with bits {2,5,6} set, generate the smallest number with 6 set bits that has bit {2,5,6} set, and then the number after that etc
| Solution 1 (based on "Snoobing the Universe")
One solution is to define a value corresponding to the "fixed bits" and one corresponding to the "variable bits".
E.g. for bits {2, 5, 6}, the "fixed bits" value would be 0x64 (assuming bits are counted starting from 0).
The "variable bits" is initialized with the smallest value having the remaining number of bits. E.g. if we want a total of 6 bits and have 3 fixed bits, the remaining number of bits is 6-3=3, so the "variable bits" starting value is 0x7.
Now the resulting value is calculated by "blending" the two bit sets by inserting the "variable bits" into the places where the "fixed bits" are 0 (see the function blend() below).
To get the next value, the "variable bits" are modified using the linked "Snoobing the Universe" function (snoob() below) and the result is again obtained by "blending" the fixed and variable bits.
All in all, a solution is as follows (prints the first 10 numbers as an example):
#include<stdio.h>
#include<stdint.h>
uint64_t snoob (uint64_t x) {
uint64_t smallest, ripple, ones;
smallest = x & -x;
ripple = x + smallest;
ones = x ^ ripple;
ones = (ones >> 2) / smallest;
return ripple | ones;
}
uint64_t blend(uint64_t fixed, uint64_t var)
{
uint64_t result = fixed;
uint64_t maskResult = 1;
while(var != 0)
{
if((result & maskResult) == 0)
{
if((var & 1) != 0)
{
result |= maskResult;
}
var >>= 1;
}
maskResult <<= 1;
}
return result;
}
int main(void)
{
const uint64_t fixedBits = 0x64; // Bits 2, 5, 6 must be set
const int additionalBits = 3;
uint64_t varBits = ((uint64_t)1 << additionalBits) - 1;
uint64_t value;
for(unsigned i = 0; i < 10; i++)
{
value = blend(fixedBits, varBits);
printf("%u: decimal=%llu hex=0x%04llx\n", i, value, value);
varBits = snoob(varBits); // Get next value for variable bits
}
}
Solution 2 (based on "Snoobing any Sets")
Another solution based on the linked "Snoobing any Sets" (function snoobSubset()below) is to define the "variale set" as the bits which are not fixed and then initialize the "variable bits" as the n least significant of these bits (see function getLsbOnes() below). In the example case, n=3.
This solution is as follows:
#include<stdio.h>
#include<stdint.h>
uint64_t getLsbOnes(uint64_t value, unsigned count)
{
uint64_t mask = 1;
while(mask != 0)
{
if(count > 0)
{
if((mask & value) != 0)
{
count--;
}
}
else
{
value &= ~mask;
}
mask <<= 1;
}
return value;
}
// get next greater subset of set with same number of one bits
uint64_t snoobSubset (uint64_t sub, uint64_t set) {
uint64_t tmp = sub-1;
uint64_t rip = set & (tmp + (sub & (0-sub)) - set);
for(sub = (tmp & sub) ^ rip; sub &= sub-1; rip ^= tmp, set ^= tmp)
tmp = set & (0-set);
return rip;
}
int main(void)
{
const uint64_t fixedBits = 0x64;
const int additionalBits = 3;
const uint64_t varSet = ~fixedBits;
uint64_t varBits = getLsbOnes(varSet, additionalBits);
uint64_t value;
for(unsigned i = 0; i < 10; i++)
{
value = fixedBits | varBits;
printf("%u: decimal=%llu hex=0x%04llx\n", i, value, value);
varBits = snoobSubset(varBits, varSet);
}
}
Example output
The output for both solutions should be:
0: decimal=111 hex=0x006f
1: decimal=119 hex=0x0077
2: decimal=125 hex=0x007d
3: decimal=126 hex=0x007e
4: decimal=231 hex=0x00e7
5: decimal=237 hex=0x00ed
6: decimal=238 hex=0x00ee
7: decimal=245 hex=0x00f5
8: decimal=246 hex=0x00f6
9: decimal=252 hex=0x00fc
|
69,772,694 | 69,772,726 | Why is the output "0x7ffffcf9a010"? | #include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars;
return 0;
}
Why is it returning 0x7ffffcf9a010 when I output it?
| Yes, it will output that, the strange number you see is the address of the starting of the first element of the array, cars is implicitly converted to a pointer. By itself, it's an array rather than a pointer.
You want to do this,
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
//cout << cars[0]; // To print the first element
for(int i = 0; i < 4; i++)
{
// To print all the elements one by one with a new line in between each element
cout<<cars[i] << '\n';
}
return 0;
}
|
69,772,803 | 69,772,873 | Why do i need to give input twice in order for the code to run | I am writing a simple bit of code to get a piece of text outputted a certain amount of times accoring to user input, however when running in terminal, i need to type in the number twice (so e.g. : 5 [enter] 5 [enter], then the text would be output 5 times).
Just wondering why this is and how to fix this, many thanks.
#include <iostream>
using namespace std;
int main() {
int x;
int i;
cout << "How many times do you want me to say [London Town], Numbers only" << end;
while (true) {
cin >> x;
if (!cin) {
cout << "Please type a number not text" << endl;
cin.clear();
cin.ignore(numeric_limits < streamsize > ::max(), '\n');
continue;
} else break;
}
cin >> x;
for (int i = 0; i < x; i++) {
std::cout << "London Town \n";
}
}
| You read into x two times, so you need to enter it twice.
You can fix this by removing one of the cin >> x's.
e.g.:
#include <iostream>
using namespace std;
int main() {
int x;
int i;
cout << "How many times do you want me to say [London Town], Numbers only" << end;
while (true) {
cin >> x;
if (!cin) {
cout << "Please type a number not text" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
continue;
} else break;
}
for (int i = 0; i < x; i++) {
std::cout << "London Town \n";
}
}
The int i; in main is not used, so you could also remove it.
If you want you can also combine the while loop with the if statement.
e.g:
#include <iostream>
#include <limits>
int main() {
std::cout << "How many times do you want me to say [London Town], Numbers only" << std::endl;
int x;
while(!(std::cin >> x)) {
std::cout << "Please type a number not text" << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
for (int i = 0; i < x; i++) {
std::cout << "London Town \n";
}
}
example godbolt
|
69,772,900 | 69,773,187 | How do I replace spaces with std::regex_replace between markers using non-capture groups? | I'm trying to eliminate whitespaces in a string with a regular expression. From the following snippet:
std::string in = "abc> <def\n"
"xyz> \n";
std::regex re = R"((?:>)\s+(?:<)|\s+$)";
std::string out = std::regex_replace(in, re, "(newcontent)");
I'm expecting out to contain
abc>(newcontent)<def
xyz>(newcontent)
but, alas, I get
abc(newcontent)def
xyz>(newcontent)
instead. To me it seems that the non-capture sequence (?:...) isn't working. I've tried to modify the program with extensions as std::regex re ("....", std::regex::ECMAScript | std::regex::nosubs); and appending , std::regex_constants::format_default to regex_replace to no avail. Can this be a library implementation problem or am I at fault?
| If the > and < are captured, they can be written back.
This way there are no assertion compatibility issues.
(>)\s+(<)|\s+$
replace
$1(newcontent)$2
https://regex101.com/r/dOjUlw/1
|
69,773,453 | 69,773,563 | Template operator() specialization for a special type? | I have a Vector class that is template based.
I have a unit conversion template that is based on Scott Meyers Dimensional Analysis in C++. I'm not going to list it as it is complex, unless the problem can't be solved without those details. I'm using the casting operator for when I need to pass the data to outside functions.
template<typename T>
struct XYZVector
{
operator Point3D() { return Point3D(x, y, z); }
}
If I use T as a double it works fine. But when I do this I need a specialization.
Point3D vecOut = XYZVector<Unit::usFoot>(x,y,z);
Will fail because when converting a Unit object you need to use an as() method.
operator Point3D() { return Point3D( x.as<T>(), y.as<T>(), z.as<T>() ); }
So I need someway to say if T is a Unit use this line, other wise use the next line.
template<typename T>
struct XYZVector
{
//if typename T is a Unit type use this
operator Point3D() { return Point3D( x.as<T>(), y.as<T>(), z.as<T>() ) }
//otherwise use this
operator Point3D() { return Point3D(x, y, z); }
}
Is this possible?
| if constexpr to the rescue.
operator Point3D() {
if constexpr (std::is_same_v<std::remove_cvref_t<T>,Unit>){
return Point3D(x.as<T>(),y.as<T>(),z.as<T>());
}else{
return Point3D(x,y,z);
}
}
|
69,773,594 | 69,775,201 | C++ combine maps of enums | Let's imagine I have some class hierarchy for a game. Like this:
PhysicalObject is parent of BaseUnit is parent of BaseArcher and so on...
And each hierarchy level adds its own stats.
Any PhysicalObject - has speed and size.
Any BaseUnit - hit points.
I want it to be used as enums, so:
enum class PhysicalObjectStats { speed, size };
enum class BaseUnitStats { hitpoints };
Of course, BaseArcher must include stats of PhysicalObject and BaseUnit.
How to make such an architecture?
I've tried to implement it in such a simple way, using just map and dynamic polymorphism, but it doesn't compile (with a good reason, honestly):
https://coliru.stacked-crooked.com/a/8496247abd3e6f41
Also, I've tried to create a specific StatsHolder class and it works, but looks awful in all possible use-cases (setting and getting values). Actually, I cannot get value outside of class without down-casting:
https://coliru.stacked-crooked.com/a/46f4f4aec6a22c57
In addition, my stats may be not only int, but also bool and some other types. I tried to use std::variant for them and it works fine, but I don't want to think about it, using "GetStats()" method. So, ideally I want to have such an interface:
std::shared_ptr<PhysicalObject> unit = std::make_shared<BaseUnit>();
unit->SetValue<int>(PhysicalObjectStats::speed);
std::cout << unit->GetValue<bool>(BaseUnitStats::HasArmor);
And this makes the task even more difficult. Any suggestions of how it may be done in a good way?
| I don't see the point of map and enum whereas regular member seems to do the job:
struct PhysicalObject
{
int speed = 0;
int size = 0;
};
struct BaseUnitStats : PhysicalObject
{
// or composition:
// physicalObject PhysicalObject;
int hitpoints = 0;
};
For your StatsHolder class:
template<class StatsEnum>
struct StatsHolder
{
void SetStats(StatsEnum stat, int value) { stats[stat] = value; }
int GetStats(StatsEnum stat) const { return stats.at(stat); }
private:
std::map<StatsEnum, int> stats;
};
Derived classes have to use using:
struct BaseUnit : PhysicalObject, StatsHolder<BaseUnitStats> {
using PhysicalObject::GetStats;
using StatsHolder<BaseUnitStats>::GetStats;
using PhysicalObject::SetStats;
using StatsHolder<BaseUnitStats>::SetStats;
BaseUnit() { SetStats(BaseUnitStats::hitpoints, 300); }
};
Demo
|
69,773,745 | 69,773,857 | LDFLAGS not read in Makevars.win when building an Rcpp package | Short and sweet:
I'm writing an Rcpp package that uses zlib and sqlite.
In the following Makevars.win file, I set Compiler flags and try to set some targets.
PKG_CPPFLAGS=-I. -I./lib/sqlite/ -fopenmp -march=native -g -O2 -msse2 -fstack-protector -mfpmath=sse\
-DRSQLITE_USE_BUNDLED_SQLITE \
-DSQLITE_ENABLE_RTREE \
-DSQLITE_ENABLE_FTS3 \
-DSQLITE_ENABLE_FTS3_PARENTHESIS \
-DSQLITE_ENABLE_FTS5 \
-DSQLITE_ENABLE_JSON1 \
-DSQLITE_ENABLE_STAT4 \
-DSQLITE_SOUNDEX \
-DRCPP_DEFAULT_INCLUDE_CALL=false \
-DRCPP_USING_UTF8_ERROR_STRING \
-DBOOST_NO_AUTO_PTR \
-DSQLITE_MAX_LENGTH=2147483647 \
-DHAVE_USLEEP=1
PKG_CXXFLAGS=$(CXX_VISIBILITY)
PKG_CFLAGS=$(C_VISIBILITY)
LDFLAGS=-fstack-protector
PKG_LIBS = lib/sqlite/sqlite3.o lib/zlib/adler32.o lib/zlib/compress.o lib/zlib/crc32.o lib/zlib/deflate.o lib/zlib/gzclose.o lib/zlib/gzlib.o lib/zlib/gzread.o lib/zlib/gzwrite.o lib/zlib/infback.o lib/zlib/inffast.o lib/zlib/inflate.o lib/zlib/inftrees.o lib/zlib/trees.o lib/zlib/uncompr.o lib/zlib/zutil.o #-Llib/sqlite/ -lsqlite3
.PHONY: all
all: $(SHLIB)
$(SHLIB): $(PKG_LIBS)
(Emphasis on the -fstack-protector flag)
In spite of this, the linker line in the build window is:
C:/rtools40/mingw64/bin/g++ -std=gnu++11 -shared -s -static-libgcc -o OptiLCMSmzDB.dll tmp.def RcppExports.o base64.o mzDBReader.o mzDBWriter.o mzMLReader.o query_mzDB.o spectrum.o lib/sqlite/sqlite3.o lib/zlib/adler32.o lib/zlib/compress.o lib/zlib/crc32.o lib/zlib/deflate.o lib/zlib/gzclose.o lib/zlib/gzlib.o lib/zlib/gzread.o lib/zlib/gzwrite.o lib/zlib/infback.o lib/zlib/inffast.o lib/zlib/inflate.o lib/zlib/inftrees.o lib/zlib/trees.o lib/zlib/uncompr.o lib/zlib/zutil.o -LC:/PROGRA~1/R/R-40~1.4/bin/x64 -lR
A little long, but notice that our favorite flag is missing. As a result, the linker confronts me with several hundred instances of the following:
undefined reference to `__stack_chk_fail'`
I'm compiling on windows 10 using rtools40 with -std=gnu++11
I would greatly appreciate any suggestions.
| There are a lot of things going on there we need to decompose.
First off, you managed to have SHLIB use your enumerated list of object files. Good! I recently had to the same and I used a OBJECTS list. I think you may get lucky if you stick the -fstack-protector into PKG_LIBS because the PKG_* variables are there for your expand on the defaults use (in the hidden Makefile controlled by R). Whereas ... LDFLAGS may just get ignored.
Otherwise, I would recommend to sample among the 4000+ CRAN packages with compiled code. Some will set similar things, the search with the 'CRAN' "org" at GitHub is crude but better than nuttin'. Good luck!
Edit: You could look at my (more complicated still) Makevars.win for RInside. I just grep'ed among all the repos I have here and I don't have a current example of anybody setting -fSOMETHING on Windows.
Edit 2: I do actually have a better example for your. Each and every RcppArmadillo package uses
PKG_CXXFLAGS = -I../inst/include -I. $(SHLIB_OPENMP_CXXFLAGS)
PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS)
where the (R-system-level variable) SHLIB_OPENMP_CXXFLAGS expands to -fopenmp. So I really do think you want PKG_LIBS as stated above.
|
69,774,068 | 69,774,122 | Why use thread_local inside functions? | I thought functions are thread safe if they don't modify non-local data.
My assumption is correct according to this answer. But, recently I came across this code,
int intRand(const int & min, const int & max) {
static thread_local std::mt19937 generator;
std::uniform_int_distribution<int> distribution(min,max);
return distribution(generator);
}
The code left me puzzled. Why does it use thread_local if functions are already thread safe?
| The random number generators of the standard library (including the std::mt19937 used in the example) may not be used unsequenced in multiple threads. thread_local guarantees that each thread has their own generator which makes it possible to call the function unsequenced from multiple threads.
I thought functions are thread safe if they don't modify non-local data.
Static storage is non-local. This is true even when the variable with static storage duration is a local variable. The name is local; the storage is global.
|
69,774,178 | 69,774,875 | Boost process open process in new window (Windows) | I'm trying to design a program that uses workers processes - which are just a different program written in C++.
I start a worker process like so:
auto worker = boost::process::child("./worker.exe");
worker->detach();
The issue is, is that the worker processes are outputting information to the same command line window that they are spawned from. This is cluttering the output of the program. Ideally I want each process to run in its own window.
Is this possible using boost::process? I've only found information about hiding the window.
I'm using Windows and Visual Studio 2019.
Thanks
| ITNOA
As you can see in Boost::process hide console on windows, you can create new mode for creating process.
CreateProcessA function system call, Show yourself to how to create new process with new console, by helping creation flags: CREATE_NEW_CONSOLE (thanks to Using multiple console windows for output)
you can write code like below
struct new_window
: ::boost::process::detail::handler_base
{
// this function will be invoked at child process constructor before spawning process
template <class WindowsExecutor>
void on_setup(WindowsExecutor &e) const
{
e.creation_flags = ::boost::detail::winapi::CREATE_NEW_CONSOLE_;
}
};
and for using this, you can just write something like below
::boost::process::child ch("./worker.exe", new_window);
|
69,774,751 | 69,779,226 | Cppcheck ignores -i and checks all files after clean build | My project has pretty complex structure.
It looks something like this:
App/
Inc/
Src/
OtherDir/
ManyOtherDirsInc/
ManyOtherDirsSrc/
OtherDirs/ThatAre/Inside/OtherDirs/Inc
build/
I am building it using CMake with extra compile_commands.json.
In order to run CppCheck I am using VsCode task that runs this (massive) command:
cppcheck --addon=${workspaceFolder}/misra.json
--cppcheck-build-dir=${workspaceFolder}/build
-D__GNUC__ --enable=warning,style,performance,portability,information
--suppress=missingIncludeSystem --suppress=unmatchedSuppression
--project=${workspaceFolder}/build/compile_commands.json
-i${workspaceFolder}/ParentFolderOfManyOtherDirs/WithOtherDirsInside
-i${workspaceFolder}/OtherDirs/ThatAlsoShouldBeRecursivelyIgnored
--quiet --template=gcc --verbose
Does that mean that -i is not recursive? That would be strange, because when adding folders they are added recursively.
I would be very thankful for any help.
| The problem was that .h files where still checked, despite -i flag.
Solution:
--supress-lists=suppressions.txt
suppressions.txt
*:/home/Projects/Full/Path/*
Important note!
path in suppressions MUST be full, relative doesn't work for some reason. It is kinda problematic for a project with multiple devs. Some script that will auto-generate this file is needed.
|
69,775,181 | 69,775,715 | How can a unqualified-id contain a unqualified-name in a function call? | In C++ draft ISO(N4901/2021) 6.5.4 (Argument-dependent name lookup) we have:
When the postfix-expression in a function call (7.6.1.3) is an
unqualified-id, and unqualified lookup (6.5.3) for the name in the
unqualified-id does not find any
(1.1) — declaration of a class
member, or (1.2) — function declaration inhabiting a block scope, or
(1.3) — declaration not of a function or function template
I can't figure out a example of an unqualified-id that contains a unqualified name(with the two being different). Draft gives the following example, but i couldn't say what is what in the (f)(s):
namespace N {
struct S { };
void f(S);
}
void g() {
N::S s;
f(s); // OK: calls N::f
(f)(s); // error: N::f not considered; parentheses prevent argument-dependent lookup
}
|
I can't figure out a example of an unqualified-id that contains a unqualified name(with the two being different).
The wording doesn't say «unqualified name». And seem to miss the word «component» before «name».
Here is an example:
namespace N
{
struct S { };
template<typename>
void f(S);
}
void g()
{
N::S s;
f<int>(s); // OK: ADL finds N::f
}
An unqualified-id here is f<int> (which is a template-id) and the lookup is performed for its (component) name f.
[expr.prim.id.unqual]/2:
A component name of an unqualified-id U is
— U if it is a name or
— the component name of the template-id or type-name of U, if any.
[temp.names]/2
The component name of a simple-template-id, template-id, or template-name is the first name in it.
The term «name» is defined in [basic.pre]/4:
A name is an identifier ([lex.name]), operator-function-id ([over.oper]), literal-operator-id ([over.literal]), or conversion-function-id ([class.conv.fct]).
|
69,775,319 | 69,775,373 | c++ char array to char pointer in struct | I have a struct containing a char pointer and I have a char array containing data. I would like to have the data within the char array copied to the char pointer.
I have tried strcpy and strncpy but I get a seg fault on both, when trying to copy the data over. I cant figure out what I am doing wrong.
struct
struct Message
{
Header hdr;
char *dataArr;
Footer ftr;
};
main
int main(){
// create message struct
Message send1;
// create stream
std::ostringstream outStream;
//
// STREAM GETS DATA HERE
//
std::string temp = outStream.str();
char arr[temp.size()];
strcpy(arr, temp.c_str());
int sz = sizeof(arr)/sizeof(char);
// print arr size and contents
std::cout << "arr size: " << sz << "\n";
for(int i=0; i<sz; i++){
std::cout << arr[i];
}
// copy char array into structs char pointer
//strncpy(send1.dataArr, arr, sz);
strcpy(send1.dataArr, arr); <-- Segmentation fault here
return 0;
}
| You first need to allocate memory to copy your data.
Or use strdup that will do it for you
|
69,775,383 | 69,775,445 | C++ Forwarding on variadic values which are not rvalue references | Consider:
template <typename... Args>
void foo(Args... args) {
bar(std::forward<Args>(args)...);
}
template <typename... Args>
void foo2(Args&&... args) {
bar(std::forward<Args>(args)...);
}
I understand the perfect rvalue references forwarding in case of foo2, but what is the purpose of forwarding the variadic argument values of foo?
What would be different if foo would look like this?
template <typename... Args>
void foo(Args... args) {
bar(args...);
}
| It's not the same thing.
In this
template <typename... Args>
void foo(Args... args) {
bar(std::forward<Args>(args)...);
}
Args will never be deduced to be a reference (foo(Args...) means foo's taking the arguments by value, not by reference);
on the other hand std::forward<T>(t) is nothing more than static_cast<T&&>(t), just with a more explicit intent from the programmer;
The two things together sum up to static_cast<Args&&>(args)... having an rvalue reference return type, i.e. returning an rvalue (because Args is not a reference, so no reference collapsing can occur between Args and && to give an lvalue reference return type, which would mean an lvalue return value).
So no, there's no perfect forwarding in your first version of foo. The std::forward in it unconditionally casts its arguments to rvalues; and that's typically std::move's job:
// this is equivalent to the code above
template <typename... Args>
void foo(Args... args) {
bar(std::move(args)...);
}
|
69,775,421 | 69,775,634 | no operator "<<" matches these operands recursive tower of hanoi error | I'm new to c++ and working on a recursive towers of hanoi project. I have it completely done except for one small error. The second << in "cout << "Number of moves " << count; is giving me the error "no operator "<<" matches these operands". I understand it has something to do with count, but I am uncertain on how to fix it.
EDIT: There is also this error for the same line
Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'overloaded-function'
CODE:
#pragma warning(disable: 4996)
#include<string>
#include<stdlib.h>
#include<time.h>
#include<iostream>
#include<cmath>
using namespace std;
void toh(int p, char from, char to, char a){
static int count = 0;
if (p == 0) {
return;
} //if end
if (p == 1) {
cout << "from " << from << " to " << to << endl;
count++;
return;
} //if end
toh(p - 1, from, a, to);
cout << "from " << from << " to " << to << endl;
count++;
toh(p - 1, a, to, from);
} //toh end
int main() {
int num; bool t = 1;
do {
cout << "Enter the No. of the disks : ";
cin >> num;
cout << "source 1 target 2 temporary 3" << endl;
toh(num, '1', '2', '3');
cout << "2 to the " << num << " power = " << pow(2, num) << endl;
cout << "Number of moves " << count;
cout << "Continue? (1=yes 0=no) : ";
cin >> t;
} while (t);
system("pause");
return 0;
} //main end
| The variable count is defined local to the function toh, so you can return the count value which can be assigned to a variable called count inside main, allowing you to use it in the line cout << "Number of moves " << count;. It should look like this:
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <cmath>
using namespace std;
static int toh(int p, char from, char to, char a){
static int count = 0;
if (p == 0) {
return count;
} //if end
if (p == 1) {
cout << "from " << from << " to " << to << endl;
count++;
return count;
} //if end
toh(p - 1, from, a, to);
cout << "from " << from << " to " << to << endl;
count++;
toh(p - 1, a, to, from);
return count;
} //toh end
int main() {
int num, count; bool t = 1;
do {
cout << "Enter the No. of the disks : ";
cin >> num;
cout << "source 1 target 2 temporary 3" << endl;
count = toh(num, '1', '2', '3');
cout << "2 to the " << num << " power = " << pow(2, num) << endl;
cout << "Number of moves " << count;
cout << "Continue? (1=yes 0=no) : ";
cin >> t;
} while (t);
system("pause");
return 0;
} //main end
|
69,775,849 | 69,776,619 | how to group many radio buttons into 3 groups in C++? | My goal is to create 5 groups of radio buttons (i know it contradict with the title but you still get the point) for user choice using only Win32 API (so no window form here).
I tried using a combination of groupbox and SetWindowLongPtr but it still not working as expected (note that im using GWLP_WNDPROC as the index). If i use SetWindowLongPtr to a group box then that groupbox is gone and everything else work as expected.
I could use a "virtual" group box but it reduce the efficency of my code. Some one might recommend using WS_GROUP but it only apply if there are 2 group of radio buttons ( I think ). And i also dont like using resource so is there any solution to this problem or i just have to stuck with the "virtual" group box?
Minimal reproducible sample:
#include <Windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wp, LPARAM lp)
{
switch (uMsg)
{
default:
return DefWindowProc(hwnd, uMsg, wp, lp);
}
}
int WINAPI wWinMain(HINSTANCE hinst, HINSTANCE hiprevinst, PWSTR nCmdLine, int ncmdshow)
{
const wchar_t CLASS_NAME[] = L"Sample";
WNDCLASS wc = { };
wc.lpfnWndProc = WndProc;
wc.hInstance = hinst;
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
RegisterClass(&wc);
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
L"Sample window",
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, // Window style
CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,
NULL,
NULL,
hinst,
NULL);
HWND groupbox = CreateWindowEx(0, L"Button", L"Groupbox", WS_VISIBLE | WS_CHILD | BS_GROUPBOX, 10, 10, 100, 100, NULL, NULL, hinst, NULL);
HWND radiobutton1 = CreateWindowEx(0, L"Button", L"Groupbox", WS_VISIBLE | WS_CHILD | BS_AUTORADIOBUTTON, 10, 10, 60, 60, groupbox, NULL, hinst, NULL);
SetWindowLongPtr(groupbox, GWLP_WNDPROC, (LONG)WndProc);
SendMessage(groupbox, NULL, NULL, TRUE);
ShowWindow(hwnd, ncmdshow);
MSG msg;
while (GetMessage(&msg, NULL, NULL, NULL))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
Due to i stripped so much of the necessary function away, you need to go to task manager and kill the process named "Autoclicker" for some reason to be able to recompile it again
| Make sure you handle WM_DESTROY otherwise window won't close properly.
The radio buttons, all child dialog items, and all child windows should be created in WM_CREATE section of parent window. They need the HWND handle from parent window.
SetWindowLongPtr(.. GWLP_WNDPROC ...) is an old method used for subclassing. Your usage is incorrect. You don't need it anyway.
It's unclear what SendMessage(groupbox, NULL, NULL, TRUE); is supposed to do.
Just add the radio buttons, make sure the first radio button has an added WS_TABSTOP|WS_GROUP as shown below
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wp, LPARAM lp)
{
switch (uMsg)
{
case WM_CREATE:
{
HINSTANCE hinst = GetModuleHandle(0);
auto add = [&](const wchar_t* name,
int id, int x, int y, int w, int h, bool first = false)
{
DWORD style = WS_VISIBLE | WS_CHILD | BS_AUTORADIOBUTTON;
if (first) style |= WS_GROUP | WS_TABSTOP;
return CreateWindowEx(0, L"Button", name, style,
x, y, w, h, hwnd, (HMENU)id, hinst, NULL);
};
HWND groupbox1 = CreateWindowEx(0, L"Button", L"Groupbox1",
WS_VISIBLE | WS_CHILD | BS_GROUPBOX, 2, 2, 250, 120, hwnd, NULL, hinst, NULL);
HWND radio1 = add(L"radio1", 1, 10, 30, 200, 20, true);
HWND radio2 = add(L"radio2", 2, 10, 51, 200, 20);
HWND radio3 = add(L"radio3", 3, 10, 72, 200, 20);
HWND radio4 = add(L"radio4", 4, 10, 93, 200, 20);
HWND groupbox2 = CreateWindowEx(0, L"Button", L"Groupbox2",
WS_VISIBLE | WS_CHILD | BS_GROUPBOX, 280, 2, 250, 120, hwnd, NULL, hinst, NULL);
HWND radio11 = add(L"radio1", 11, 300, 30, 200, 20, true);
HWND radio12 = add(L"radio2", 12, 300, 51, 200, 20);
HWND radio13 = add(L"radio3", 13, 300, 72, 200, 20);
HWND radio14 = add(L"radio4", 14, 300, 93, 200, 20);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, uMsg, wp, lp);
}
}
int WINAPI wWinMain(HINSTANCE hinst, HINSTANCE hiprevinst, PWSTR nCmdLine, int ncmdshow)
{
const wchar_t CLASS_NAME[] = L"Sample";
WNDCLASS wc = { };
wc.lpfnWndProc = WndProc;
wc.hInstance = hinst;
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
RegisterClass(&wc);
HWND hwnd = CreateWindowEx(0, CLASS_NAME, L"Sample window",
WS_OVERLAPPEDWINDOW, 0, 0, 800, 600,
NULL, NULL, hinst, NULL);
ShowWindow(hwnd, ncmdshow);
MSG msg;
while (GetMessage(&msg, NULL, NULL, NULL))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
|
69,775,973 | 69,776,755 | Why cout<<++i + ar[++i]; and cout<<ar[++i]+ ++i; give different output? | I have read about undefined behaviour.
This Link says a[i] = a[i++] leads to undefined behaviour.
But I don't understand why the output of
int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i = 0;
cout << arr[++i] + ++i << " " << i;
is 3 2
and the output of
int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i = 0;
cout << ++i + arr[++i] << " " << i;
is 4 2
| Firstly - a[i] = a[i++] is well-defined since C++17. The sequencing rules were considerably tightened in that revision of the Standard, and the evalution of the right-hand side of an assignment operator is sequenced before the evaluation of the left hand side, meaning that all side-effects of the right-hand side must be complete before evaluation of the left-hand side begins.
So that code is equivalent to a[i+1] = a[i]; ++i;
Since C++17, the << operator also has left-right sequencing, i.e. the left operand is sequenced before the right operand.
Now, ++i is defined as i+=1 and similar considerations as above apply to the evaluation of the compound assignment operator. The ++i occurs "atomically" we could say.
However, the + operator is still unsequenced, this is defined by [intro.execution]/17:
Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.
[...]
If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not
potentially concurrent, the behavior is undefined
Unfortunately this means the behaviour of ++i + a[++i] is still undefined, because the left operand of + modifies i, and the right operand of + modifies i, and those operand evaluations are unsequenced relative to each other.
It has previously been proposed to make + and similar operators be left-right sequenced as well, but apparently this hasn't been accepted into the Standard yet.
|
69,775,993 | 69,776,254 | ncurses how to use setcchar function | Currently using WSL2, C++20, -lpanelw -lncursesw, #define NCURSES_WIDECHAR 1, #include <panel.h>.
I'm trying to figure out how to create cchar_t types using the setcchar() function. The function requires a location to store the cchar_t struct specified in the parameter const cchar_t *wcval.
I couldn't find any tutorials on this, so I tried a couple of approaches, but they all produced errors.
cchar_t* ptr;
setcchar(ptr, L"", 0, 0, nullptr);
cchar_t* ptr {NULL};
setcchar(ptr, L"", 0, 0, nullptr);
cchar_t* ptr {nullptr};
setcchar(ptr, L"", 0, 0, nullptr);
| I was able to solve this problem through this approach:
cchar_t ptr;
setcchar(&ptr, L"", 0, 0, nullptr);
|
69,776,246 | 69,801,624 | vs code is throwing #include error on macOS monterey it worked fine on BigSur | I updated to macOS monterey yesterday and my vs code is not compiling any code since then. It is throwing these errors :
#include errors detected. Please update your includePath. Squiggles are
disabled for this translation unit (/Users/ishudhariwal/contest.cpp).
cannot open source file "endian.h" (dependency of "iostream")
It was working perfectly fine on BigSur. I am a beginner at programming. I can't figure out what's going wrong and how to fix it.
| Try installing Xcode Command-line Tools. Most probably this will solve the issue.
Try the following.
Go to https://developer.apple.com/download/all/
Login or sign up
Look for: "Command Line Tools for Xcode 13.x" in the list of downloads then click the dmg and download.
Install it.
|
69,776,250 | 69,776,276 | heap corruption when free() struct pointer after memcpy | I'm writing a generic sorting function with C using Visual Studio 2019.
I made an generic insertion sort function with prototype:
void insertion_sort(void* const arr, size_t left, size_t right, size_t width, _Cmpfun cmp)
where _Cmpfunc is typedef as
typedef int (*_Cmpfun) (const void*, const void*);
To test this function working I made an structure ELEMENT for the test like this.
typedef struct {
unsigned int score;
float data[3];
char comments[16];
} ELEMENT;
In order to save a data, I dynamically allocated memory like this.
char* top_ptr = (char*)malloc(sizeof(width));
Whenever I try to free() top_ptr after
memcpy(top_ptr, some_valid_pointer, width)
where some_valid_pointer is not NULL pointer and width is parameter of insertion_sort
, Visual Studio pops Heap corruption error.
This happens only after memcpy function is called.
If I do like this :
char* top_ptr = (char*)malloc(sizeof(width));
free(top_ptr);
it works fine.
I've search what is Heap corruption error in the web and found it occurs when memcpy function overwrites the invalid memory of structure variable.
I call function insertion_sort with width = sizeof(ELEMENT) in main so padding of struct variable is considered.
I have no idea what is the problem. What is wrong with my code?
| width = sizeof(ELEMENT)
sizeof(ELEMENT), using back-of-the-envelope calculations, should be be in the neighborhood of about 30 bytes. That's how big your ELEMENT is.
char* top_ptr = (char*)malloc(sizeof(width));
Since width is a size_t, sizeof(size_t) will be either 4 or 8, depending upon whether you're compiling 32 or 64 bit code.
So, this will allocate 4 or 8 bytes. Far short of 30 bytes being memcpyed.
That's your heap corruption, right here.
|
69,776,441 | 69,776,483 | comparing one array element with the next element to find what is the biggest element | I'm trying to find a way to iterating while comparing the element with the next element to find what is the biggest element in the array. But, the output i want keep repeating as much as the loop run.
int main(){
int array[4];
for ( int i = 0; i < 4; i++){
cin >> array[i];
}
for (int i:array){
for (int j = 1; j < 4; j++){
if (i < array[j]){
break;
}
if (i > array[j] ){
cout << i;
}
}
}
}
| You can use the following program to find the biggest element in the array. Note that there is no need to use two for loops as you did in your code snippet.
#include <iostream>
int main()
{
int array[4] = {1,10, 13, 2};
int arraySize = sizeof(array)/sizeof(int);//note that you can also use std::size() with C++17
int startingValue = array[0];
for(int i = 1; i < arraySize; ++i)//start from 1 instead of 0 since we already have array[0]
{
if(array[i] > startingValue)
{
startingValue = array[i];
}
}
//print out the biggest value
std::cout<<"the biggest element in the array is: "<<startingValue<<std::endl;
return 0;
}
Your program is reapeating output because you have the cout inside the if which is satisfied multiple times(depending upon how big the array is and what elements it contains). For example, if you try your example on the array int array[] = {23,2,13,6,52,9,3,78}; then the output of your program will be 2323231313652525293787878 . So the output is reapeating more than 2 times. You can instead use the version i gave that uses only 1 for loop and prints the correct biggest element only once.
Note that you can also use std::size with C++17 while sizeof(array)/sizeof(int) works with all C++ versions.
|
69,776,623 | 69,776,693 | How to link to libraries downloaded with Homebrew in Visual Studio Code? | I just downloaded GTKMM using Homebrew but I don't know how to link to it with Visual Studio Code. I have a c_cpp_properties file as well as a tasks.json (Both C/C++ settings files) that I can use to link to files with.
Do I link to the downloaded package directly (opt/Homebrew/Cellar/gtkmm) or do I need to link it to somewhere else, like /Library/Frameworks/?
I am on an ARM Mac, using C++ and Visual Studio Code. I also need to make sure my project is cross-platform.
| You may install pkg-config and it will make the life of a developer sweeter:
brew install pkg-config
pkg-config --cflags --libs gtkmm
The last command shows the required compiler and linker flags for using gtkmm.
|
69,776,674 | 69,776,982 | USB Barcode Scanner with C++ Console Program | I know this isn't exactly a programming question, but it is related:
I'd like to know if USB barcode scanners can scan a barcode and type the results as if it was a keyboard.
The reason for this is that I would like to make a C++ console application that will take the input of the scanner using cin or getline, but that would only work if the barcode scanner types the results into my program like a keyboard, and I would like the scanner to press enter for me so I can just scan and scan without pressing it myself in between.
If it doesn't work like that, then how can I get the barcode scanner to give the variable with the results to my program? Is there a special cheap barcode scanner with a C++ api?
I would test this myself, but I am a teen with no money and I don't want to bother my parents for a scanner just to waste their money if it doesn't work.
EDIT: If there is some 3rd party api thing, I don't want to have to type so much confusing code, I would just like to type something like: barcodeResults = scanBarcodeAPI();
| All the barcode scanners I've dealt with have emulated a keyboard. (In fact, a more common question seems to be how to distinguish scanner input from keyboard input. For example, see How do I tell if keyboard input is coming from a barcode scanner?)
Having the scanner add <ENTER> to the end of the barcode is a common configuration (of the scanner).
|
69,776,915 | 69,777,189 | the sum of 1 + a + a^2 + _ _ _ + a^n | here is my code:
#include <iostream>
using namespace std;
int main()
{
int s = 1, i, n, m;
double a;
cin >> a >> n;
while (n <= 0)
{
cin >> n;
}
m = a;
for (i = 1; i <= n; i++)
{
s += m;
m *= a;
}
cout << s << endl;
return 0;
}
here was the start data:
Given a real number a and a natural n, calculate the sum 1 + a + a^2 + _ _ _ + a^n, without using the formula for the sum of a geometric progression. The running time of the program must be proportional to n.
Input data Enter 2 numbers - a and n.
Output It is necessary to display the value of the sum.
The checking program considers my code not full. Please explain where is the problem?
| m *= a;. m is an int type, while a is a double type
#include <iostream>
// using namespace std; is bad, so don't use it
int main()
{
// there's no need to declare a variable but leave it uninitialized.
double a{};
int n{};
std::cin >> a;
while (n <= 0)
{
std::cin >> n;
std::cin.clear();
std::cin.ignore(100, '\n');
}
double m{a};
double s{1.0}
for (int i = 1; i <= n; i++) // declare i in the loop scope
{
s += m;
m *= a;
}
std::cout << s << '\n'; // use newline character instead of std::endl
return 0;
}
|
69,777,007 | 69,777,081 | How to concurrently send data to multiple servers using C++ socket programming? | I deployed one program onto several servers (suppose the server IPs and the ports providing the service are 192.168.1.101:10001, 192.168.1.102:10001, 192.168.1.103:10001, 192.168.1.104:10001). They are all listening requests using the Linux socket apis and can finish the task independently.
Now, I want to concurrently send data to all four servers, so that they can concurrently executing the tasks.
I am sending the data using one Windows 10 PC, using C++ Socket. The basic procedure of send_data is as follows:
void send_data(string& server_ip, string& server_port, vector<char>& buf) {
struct addrinfo ...; // set the server information
SOCKET socket = socket(...); // create the socket object
connect(socket, ...); // connect the server
send(socket, buf, ...); // send the buf data
}
This is OK when sending sequentially data into the four servers, e.g.,
vector<char> bufdata(...);
char* server_ips = {"192.168.1.101", "192.168.1.102", "192.168.1.103", "192.168.1.104"};
char* port = "10001";
for (int i = 0; i < 4; ++i) {
send_data(server_ips[i], port, bufdata);
}
What I expect is the host client can concurrently send the data. I have tried the following method:
for (int i = 0; i < 4; ++i) {
std::thread t(send_data, server_ips[i], port, bufdata);
}
But the program will exit with no luck.
Could you please help give some advice? Thanks.
| Not sure this is the only problem, but given what you shared, the main thread is not waiting for the worker threads to finish their tasks.
Per this answer: When the main thread exits, do other threads also exit?, the process will be terminated when the main thread returns from main().
Proposed fix:
int main() {
// .. your logic here
std::vector<std::thread> threads;
for (int i = 0; i < 4; ++i) {
std::thread t(send_data, server_ips[i], port, bufdata);
threads.push_back(std::move(t));
}
for (int i = 0; i < 4; ++i) {
if (threads[i].joinable())
threads[i].join(); // wait for threads[i] to finish
}
// .. clean up
}
|
69,777,418 | 69,777,419 | How to deal with 'Template' and 'Docstring' simultaneously in C++ | What is the standard order of writing a class definition with associated template and docstring, to make it recognisable by the IDEs ?
Is it:
<docstring>
<template>
<class declaration/ definition>
Or:
<template>
<docstring>
<class declaration/ definition>
| The standard way of ordering template and docstring is as follows:
Docstring
Template
Class declaration / definition
Example:
/**
* Class of Traveling Salesman Problem : Ctor :-
* @param nov: order of Graph (|V|)
* @param startVertex: Starting Vertex for Hamiltonian Traversal
* @param costMatrix (optional): accepts cost matrix, if not provided, then one should call input() function
*/
template<typename DT>
class TSP
{
...
};
Sidenote : Code snippet behaviour verified on MS Visual Studio IDE
|
69,777,430 | 69,777,462 | How do you declare functions with predefined arguments? | I want to know how do u declare a function with definite arguments. It's said to be good practice to put the function declaration at the beginning , before the main() function and then its definition, but in this case the compiler gives me an error, becase it's like if it doesn't see the formal arguments.
#include <iostream>
using namespace std;
void function(int i=1, char a='A', float val=45.7);
int main()
{
function();
return 0;
}
void function(int i = 1, char a='A', float val=45.7)
{
cout << "i: " << i << endl;
cout << "a: " << a << endl;
cout << "val: " << val << endl;
}
I tried to insert the formal arguments in the declaration, but it doesn't work.
| here is the way to initialise the function args to default values.
You dont need to pass default args in defination. They should be given only in the declaration itself.
#include <iostream>
using namespace std;
void function(int i=1, char a='A', float val=45.7);
int main()
{
function();
return 0;
}
void function(int i, char a, float val)
{
cout << "i: " << i << endl;
cout << "a: " << a << endl;
cout << "val: " << val << endl;
}
Now, this code will work like a charm.
Link to working example -> http://cpp.sh/4j7lx
|
69,777,653 | 69,777,906 | OpenCV FAST Algorithm creating skewed keypoints on only part of an image | I'm trying to use OpenCV's FAST corner detection algorithm to get an outline of an image of a ball (Not my final project, I'm using it as a simple example). For some reason, it only works on a third of the input Mat, and stretches the Keypoints across the image. I'm not sure as to what could be going wrong here to make the FAST algorithm not apply to the entire Mat.
Code:
void featureDetection(const Mat& imgIn, std::vector<KeyPoint>& pointsOut) {
int fast_threshold = 20;
bool nonmaxSuppression = true;
FAST(imgIn, pointsOut, fast_threshold, nonmaxSuppression);
}
int main(int argc, char** argv) {
Mat out = imread("ball.jpg", IMREAD_COLOR);
// Detect features
std::vector<KeyPoint> keypoints;
featureDetection(out.clone(), keypoints);
Mat out2 = out.clone();
// Draw features (Normal, missing right side)
for(KeyPoint p : keypoints) {
drawMarker(out, Point(p.pt.x / 3, p.pt.y), Scalar(0, 255, 0));
}
imwrite("out.jpg", out, std::vector<int>(0));
// Draw features (Stretched)
for(KeyPoint p : keypoints) {
drawMarker(out2, Point(p.pt.x, p.pt.y), Scalar(127, 0, 255));
}
imwrite("out2.jpg", out2, std::vector<int>(0));
}
Input image
Output 1 (keypoint.x multiplied by a factor of 1/3, but missing right side)
Output 2 (Coordinates untouched)
I'm using OpenCV 4.5.4 on MinGW.
| Most keypoint detectors use grayscale images as input.
If you interpret the memory of a bgr image as grayscale, you will have 3 times the number of pixels. Y axis is still ok if the algorithm uses the width-offset per row, which most algorithms do (because this is useful when subimaging or padding is used).
I don't know whether it is a bug or a feature, that FAST doesn't check for the number of channels snd doesnt throw an exception if the wrong number of channels ist given.
You can convert the image to grayscale by cv::cvtColor with the flag cv:: COLOR_BGR2GRAY
|
69,777,742 | 69,777,894 | How can I delete a binary tree with O(1) additional memory? | I was wondering if it's possible to delete a binary tree with O(1) additional memory, without using recursion or stacks.
I have managed to write the naive, recursive postorder traversal solution (which uses stack memory):
void deleteTreeRec(Node *root)
{
if (root == NULL) return;
deleteTreeRec(root->left);
deleteTreeRec(root->right);
cout << "Deleting node " << root->data << endl;
delete root;
}
I've heard that this can be achieved using (inorder) Morris traversal, which seems wrong, or at least counterintuitive, given the fact that tree deletion requires, as far as I understand, traversal in a postorder fashion (start by deleting the two subtrees, and only afterwards, the root). However, I haven't found any detailed description/pseudocode of the solution, hence I am trying my luck here.
If anybody could shed some light on this issue, it would be greatly appreciated. Thanks!
| During the deletion the existing nodes of the binary tree can be used as a singly linked list: The nodes always using the left "link" is seen as the linked list.
To delete all nodes you simply repeat the following steps:
find the tail of the "linked list"
if right is non-null, move it to the end of the "list"
store the pointer the next element in the "list" in a temporary
replace the old head with the temporaty and repeat if the "list" is non-empty
Starting the search for the new tail at the previous tail results in the algorithm running in O(n) where n is the number of nodes in the binary tree.
void deleteTree(Node* root)
{
Node* tail = root;
while (root != nullptr)
{
// update tail
while (tail->left != nullptr)
{
tail = tail->left;
}
// move right to the end of the "list"
// needs to happen before retrieving next, since the node may only have a right subtree
tail->left = root->right;
// need to retrieve the data about the next
Node* next = root->left;
delete root;
root = next;
}
}
|
69,778,634 | 70,109,507 | SFML blending mode to interpolate colors with alpha | Assume I have a C_1 = (255, 0, 0, 127) filled sf::Texture and a sf::RenderTexture filled with C_2 = (0, 0, 0, 0). Then I call
render_texture.draw(texture);
The result given by sf::BlendAlpha is a texture filled with (127, 0, 0, 127), but my goal (for the small graphics editor app I'm writing) is blending those two colors to get (255, 0, 0, 127), because, intuitively, drawing on perfectly transparent texture is "copying color of your brush to it". I've checked formulas of sf::BlendAlpha, and it appeared to work like this:
C_res = C_src * aplha_src + C_dst * (1 - alpha_src)
Where C_src is C_1 and C_dst is C_2. But wait, does it totally ignore aplha_dst?
If I understand blending right, the formula I need is something like
alpha_sum = alppha_src + alpha_dst
C_res = C_src * alpha_src / alpha_sum + C_dst * alpha_dst / alpha_sum
Which gives adequate colors and does not ignore alpha_dst. But with BlendingMode from SFML, using different Factors and Equations, there's no chance to get division (that also introduces troubles when dealing with alpha_sum = 0). Any suggestions on how actually I should think about blending colors and painting? At least, did I get it right, that usual alpha blending used by SFML is not what graphics editors do? (tested on Aseprite, Krita, Photoshop, they blend color from the brush to (0, 0, 0, 0) as I expect)
| The solution I ended up with: writing your own blend mode with glsl and using shaders. This way you can create and formulas without the need to think about how to bring it to sfml, because it already supports shaders, that can be easily passed to any draw call.
|
69,778,684 | 69,779,046 | How can I resolve this one or more multiply defined symbol found error? | What is the bug in the following project?
main.cpp
#include "template_specialization_conflict_test.hpp"
int main()
{
std::cout << utils::my_template_function(0.555);
std::cout<<utils::my_template_function<double>(0.555);
return 0;
}
template_specialization_conflict_test.hpp
#ifndef UTILS__UTILS__UTILS__UTILS
#define UTILS__UTILS__UTILS__UTILS
#include <iostream>
namespace utils
{
// A generic function
template <class T>
T my_template_function(T parameter)
{
std::cout << "function template";
std::cout << parameter;
return parameter;
}
// Template Specialization
// A function specialized for double data type
template <>
double my_template_function<double>(double parameter)
{
std::cout << "function specialization on double";
std::cout << parameter;
return parameter;
}
}
#endif
template_specialization_conflict_test.cpp
#include "template_specialization_conflict_test.hpp"
namespace utils
{
//empty
}
Error
>------ Rebuild All started: Project: template_specialization_conflict_test, Configuration: x64-Debug ------
[1/1] Cleaning all built files...
Cleaning... 2 files.
[1/3] Building CXX object CMakeFiles\template_specialization_conflict_test.dir\main.cpp.obj
[2/3] Building CXX object CMakeFiles\template_specialization_conflict_test.dir\template_specialization_conflict_test.cpp.obj
[3/3] Linking CXX executable template_specialization_conflict_test.exe
FAILED: template_specialization_conflict_test.exe
cmd.exe /C "cd . && "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E vs_link_exe --intdir=CMakeFiles\template_specialization_conflict_test.dir --rc=C:\PROGRA~2\WI3CF2~1\10\bin\10.0.17763.0\x64\rc.exe --mt=C:\PROGRA~2\WI3CF2~1\10\bin\10.0.17763.0\x64\mt.exe --manifests -- "C:\PROGRA~2\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64\link.exe" /nologo CMakeFiles\template_specialization_conflict_test.dir\template_specialization_conflict_test.cpp.obj CMakeFiles\template_specialization_conflict_test.dir\main.cpp.obj /out:template_specialization_conflict_test.exe /implib:template_specialization_conflict_test.lib /pdb:template_specialization_conflict_test.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:console kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cd ."
LINK Pass 1: command "C:\PROGRA~2\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64\link.exe /nologo CMakeFiles\template_specialization_conflict_test.dir\template_specialization_conflict_test.cpp.obj CMakeFiles\template_specialization_conflict_test.dir\main.cpp.obj /out:template_specialization_conflict_test.exe /implib:template_specialization_conflict_test.lib /pdb:template_specialization_conflict_test.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:console kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:CMakeFiles\template_specialization_conflict_test.dir/intermediate.manifest CMakeFiles\template_specialization_conflict_test.dir/manifest.res" failed (exit code 1169) with the following output:
C:\Users\pc\source\repos\template_specialization_conflict_test\out\build\x64-Debug\main.cpp.obj : error LNK2005: "double __cdecl utils::my_template_function<double>(double)" (??$my_template_function@N@utils@@YANN@Z) already defined in template_specialization_conflict_test.cpp.obj
C:\Users\pc\source\repos\template_specialization_conflict_test\out\build\x64-Debug\template_specialization_conflict_test.exe : fatal error LNK1169: one or more multiply defined symbols found
ninja: build stopped: subcommand failed.
Rebuild All failed.
How can I fix this?
|
How can I fix this?
You could solve this by adding/using the keyword inline for the specialization so the specialization would look like:
//note the keyword inline in the below specialization
template <> inline
double my_template_function<double>(double parameter)
{
std::cout << "function specialization on double";
std::cout << parameter;
return parameter;
}
This works as can be seen here.
Second way to solve this would be to move your specialization into the source file instead of the header. So your template_specialization_conflict_test.cpp would look like:
template_specialization_conflict_test.cpp
#include "template_specialization_conflict_test.hpp"
namespace utils
{
// Template Specialization
// A function specialized for double data type
template <>
double my_template_function<double>(double parameter)
{
std::cout << "function specialization on double";
std::cout << parameter;
return parameter;
}
}
The program works as can be seen here and here(with gcc and clang).
|
69,779,369 | 69,782,699 | c++ smart pointer c'tor design explaination | When I read the code:
DefaultSPStorage() : pointee_(Default()) {}
DefaultSPStorage(const DefaultSPStorage&) : pointee_(nullptr) {}
template<class U>
DefaultSPStorage(const DefaultSPStorage<U>) : pointee_(nullptr) {}
explicit DefaultSPStorage(const StoredType& p) : pointee_(p) {}
I feel confused on the third templated c'tor.
If anyone can enlighten me the purpose of it, I would be really grateful.
| DefaultSPStorage() is a template class, eg:
template<typename T>
class DefaultSPStorage
{
...
};
The third templated constructor takes a DefaultSPStorage<U> instance whose template parameter can be different than the DefaultSPStorage instance that is being constructed.
IOW, this allows constructing a DefaultSPStorage<A> using a DefaultSPStorage<B> as input, eg:
DefaultSPStorage<short> a;
DefaultSPStorage<int> b(a);
|
69,779,958 | 69,780,016 | How does cin read strings into an object of string class? | Reading some documentation online I found that istream class was part of C++ long before the string class was added. So the istream design recognizes basic C++ types such as double and int, but it is ignorant of the string type. Therefore, there are istream class methods for processing double and int and other basic types, but there are no istream class methods for processing string objects.
My question is if there are no istream class methods for processing string objects, why this program works and how ?
#include <iostream>
int main(void)
{
std::string str;
std::cin >> str;
std::cout << str << std::endl;
return 0;
}
| This is possible with the use operator overloading. As shown in the below example, you can create your own class and overload operator>> and operator<<.
#include <iostream>
class Number
{
//overload operator<< so that we can use std::cout<<
friend std::ostream& operator<<(std::ostream &os, const Number& num);
//overload operator>> so that we can use std::cin>>
friend std::istream &operator>>(std::istream &is, Number &obj);
int m_value = 0;
public:
Number(int value = 0);
};
Number::Number(int value): m_value(value)
{
}
std::ostream& operator<<(std::ostream &os, const Number& num)
{
os << num.m_value;
return os;
}
std::istream &operator>>(std::istream &is, Number &obj)
{
is >> obj.m_value;
if (is) // check that the inputs succeeded
{
;//do something
}
else
{
obj = Number(); // input failed: give the object the default state
}
return is;
}
int main()
{
Number a{ 10 };
std::cout << a << std::endl; //this will print 10
std::cin >> a; //this will take input from user
std::cout << a << std::endl; //this will print whatever number (m_value) the user entered above
return 0;
}
By overloading operator>> and operator<<, this allows us to write std::cin >> a and std::cout << a in the above program.
Similar to the Number class shown above, the std::string class also makes use of operator overloading. In particular, std::string overloads operator>> and operator<<, allowing us to write std::cin >> str and std::cout << str, as you did in your example.
|
69,780,791 | 69,781,135 | How to store values in the boost multi_array container? | I'm struggling to access the values and store them in boost multi_array container. I've tried to access the elements using the indexing methods ([] and .at()), but throws error: no matching function for call to 'boost::multi_array<float, 2>::data(int)', however I can print the data (see the code) but do not have any idea how to store it and access it again for further computations. The data is two dimensional(11214, 3), but for the meantime I just want to flatten it and have a sequence of values. So my question is how to access the elements and how to store them in the container?
#include <boost/multi_array.hpp>
#include <boost/timer/timer.hpp>
#include <boost/range/irange.hpp>
#include <h5xx/h5xx.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
using array_2d_t = boost::multi_array<float, 2>;
//using array_2d_t = boost::multi_array<float, 3>;
template <typename T>
void print_array(T const& array)
{
for (auto const& row : array)
{ for (auto v : row)
printf("%10f ", v);
printf("\n"); //prints a new line similar t0 \n
}
}
h5xx::dataset open_dataset(std::string const& filename) {
h5xx::file xaa(filename, h5xx::file::mode::in);
h5xx::group g(xaa, "particles/lipids/box/positions");
return h5xx::dataset(g, "value");
}
std::vector<float> cell_from_all_frames(h5xx::dataset& ds, size_t row, size_t col) {
// determine dataset shape: frames, particle count, space dimension
auto ds_shape = h5xx::dataspace(ds).extents<3>();
std::vector<float> cells(ds_shape[0]); // number of frames
std::vector<hsize_t> offsets{0, row, col};
std::vector<hsize_t> counts{ds_shape[0], 1, 1};
h5xx::slice slice(offsets, counts);
h5xx::read_dataset(ds, cells, slice);
return cells;
}
array_2d_t read_frame(std::string const& filename, unsigned frame_no) {
//h5xx::file xaa("../../data/xaa.h5", h5xx::file::mode::in);
h5xx::file xaa(filename, h5xx::file::mode::in);
h5xx::group g(xaa, "particles/lipids/box/positions");
h5xx::dataset ds(g, "value");
// determine dataset shape: frames, particle count, space dimension
auto ds_shape = h5xx::dataspace(ds).extents<3>();
array_2d_t arr(boost::extents[ds_shape[1]][ds_shape[2]]);
std::vector<hsize_t> offsets{frame_no, 0, 0};
std::vector<hsize_t> counts{1, arr.shape()[0], arr.shape()[1]};
h5xx::slice slice(offsets, counts);
h5xx::read_dataset(ds, arr, slice);
return arr;
}
int main(int argc, char const* argv[])
{
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " input.h5" << std::endl;
return -1;
}
auto ds = open_dataset(argv[1]);
std::vector<float> first_cells = cell_from_all_frames(ds, 0, 0);
// set up multi-tau correlator for the computation of time correlation functions
size_t nsamples = 10; // FIXME obtain these parameters from HDF5 file. These 10 elements would be first element of first row, first element of 11214 row, first element of 11214*2 row, first element of 11214*3 row ,..., first element of 11214*10 row.
return 0;
}
In the main() I read the data from function read_frame and try to pass it to the nsamples. I've tried few things but it doesn't work!!
| You can choose.
Store it?
array_2d_t frame = read_frame(filename, 1);
Access an element?
// access individual elements:
float ele = frame[0][3];
// or with index list:
std::array<int, 2> indices{0,3};
ele = frame(indices);
Or, as you seem to want, provide a flat view of the array:
boost::multi_array_ref<float, 1> sequence(frame.origin(), boost::extents[frame.num_elements()]);
fmt::print("Sum of all {} elements: {}\n",
sequence.size(),
std::accumulate(sequence.begin(), sequence.end(), 0.f));
In fact yuou might reshape in-place, but then you cannot change dimensiaonality, so you get 1 "row" of all cells:
frame.reshape(std::array<size_t, 2> {1, frame.num_elements()});
// now the first "row" is the full sequence:
auto&& sequence = frame[0];
fmt::print("Sum of all {} elements: {}\n",
sequence.size(),
std::accumulate(sequence.begin(), sequence.end(), 0.f));
There are legion options for slicing/reindex with or without strides, but I refer to the Boost documentation to prevent needlessly complicating things here.
Live Demo
#include <boost/multi_array.hpp>
#include <fmt/ranges.h>
#include <h5xx/h5xx.hpp>
#include <iostream>
#include <iterator>
using array_2d_t = boost::multi_array<float, 2>;
h5xx::dataset open_dataset(std::string const& filename) {
h5xx::file xaa(filename, h5xx::file::mode::in);
h5xx::group g(xaa, "particles/lipids/box/positions");
return h5xx::dataset(g, "value");
}
array_2d_t read_frame(h5xx::dataset& ds, unsigned frame_no) {
auto ds_shape = h5xx::dataspace(ds).extents<3>();
array_2d_t arr(boost::extents[ds_shape[1]][ds_shape[2]]);
std::vector<hsize_t> offsets{frame_no, 0, 0};
std::vector<hsize_t> counts{1, arr.shape()[0], arr.shape()[1]};
h5xx::slice slice(offsets, counts);
h5xx::read_dataset(ds, arr, slice);
return arr;
}
std::vector<float> cell_from_all_frames(h5xx::dataset& ds, size_t row, size_t col) {
// determine dataset shape: frames, particle count, space dimension
auto ds_shape = h5xx::dataspace(ds).extents<3>();
std::vector<float> cells(ds_shape[0]); // number of frames
std::vector<hsize_t> offsets{0, row, col};
std::vector<hsize_t> counts{ds_shape[0], 1, 1};
h5xx::slice slice(offsets, counts);
h5xx::read_dataset(ds, cells, slice);
return cells;
}
int main(int argc, char const* argv[])
{
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " input.h5" << std::endl;
return -1;
}
auto ds = open_dataset(argv[1]);
array_2d_t frame = read_frame(ds, 1);
// access individual elements:
[[maybe_unused]] float ele = frame[0][2];
// or with index list:
std::array<int, 2> indices{0,2};
ele = frame(indices);
{
boost::multi_array_ref<float, 1> sequence(frame.origin(), boost::extents[frame.num_elements()]);
fmt::print("Sum of all {} elements: {}\n",
sequence.size(),
std::accumulate(sequence.begin(), sequence.end(), 0.f));
}
{
// in fact yuou might reshape in-place, but then you cannot change dimensiaonality
frame.reshape(std::array<size_t, 2> {1, frame.num_elements()});
// now the first "row" is the full sequence:
auto&& sequence = frame[0];
fmt::print("Sum of all {} elements: {}\n",
sequence.size(),
std::accumulate(sequence.begin(), sequence.end(), 0.f));
}
{
std::vector<float> first_cells = cell_from_all_frames(ds, 0, 0);
fmt::print("Sum of all {} first cells: {}\n",
first_cells.size(),
std::accumulate(first_cells.begin(), first_cells.end(), 0.f));
}
}
With your xaa.h5 from a while ago:
Sum of all 33642 elements: 737589.1
Sum of all 33642 elements: 737589.1
Sum of all 75 first cells: 6053.3496
|
69,780,970 | 69,781,122 | Cant's pass a 2D array to a function in C++ | I was following internet tutorials on this topic, but I have the following situation:
I have a function with the following signature:
void func(long& rows, long& columns, int array[][columns]);
and I'm trying to use the function like this:
int matrix[5][4] = {0, -1, 2, -3,
4, -5, 6, -7,
8, -9, 10, -11,
12, -13, 14, -15,
16, -17, 18, -19};
long rows = 5;
long columns = 4;
func(rows, columns, matrix);
^--- 'No matching function for call to 'func''
What is the problem? Why can't it call the function?
| Have you actually defined func in your program?
The following source code compiles and works fine for me
#include <iostream>
#define ROW 5
#define COLUMN 4
void func(long &rows, long &columns, int array[][COLUMN]);
int main()
{
int matrix[ROW][COLUMN] = {0, -1, 2, -3,
4, -5, 6, -7,
8, -9, 10, -11,
12, -13, 14, -15,
16, -17, 18, -19};
long rows = 5;
long columns = 4;
func(rows, columns, matrix);
return 0;
}
void func(long &rows, long &columns, int array[][COLUMN])
{
std::cout << rows << columns << array[0][1];
}
|
69,781,174 | 69,782,479 | Using the value _T("") and CString variables | This might sounds simple but I want to know if one way is actually more efficient.
Example one:
CString strName = _T("");
CString strName = CString();
Example two:
if (strFilterText == _T(""))
if (strFilterText.IsEmpty())
Is there any negative impact is using _T("") in this way? And if so, why?
| CString has different constructors and operator overloads, it is prepared for different scenarios. It's a complicated class but in general, such classes work like this:
Use default constructor CString() (initializes for _T("")):
CString s1 = CString();
CString s2; //same as above, shortcut
CString s3{}; //same as above
CString s4 = {}; //same as above
Use copy constructor CString(const CString& src):
const CString src = _T("");
CString s1 = CString(src);
CString s2 = src; //same as above
CString s3 = { src}; //same as above
CString s4(src); //same as above
Use different constructor CString(const TCHAR* src):
const TCHAR* src = _T("");
CString s1 = CString(src);
CString s2 = src; //same as above
CString s3 = { src }; //same as above
CString s4(src); //same as above
CString also supports = assignment operator:
CString s;
s = _T(""); //uses `=` assignment operator
s = CString(); //uses default constructor for right side,
//calls `=` assignment operator for left side.
== operator overload may use CString::Compare to compare the two sides. So
if (s == _T("")) is same as if (s.Compare(_T("")) == 0), it might be 1 nanosecond slower than s.IsEmpty(), otherwise is valid.
|
69,781,565 | 69,781,616 | In template<class It> function where It is an iterator, can I make It::value_type work for both vector::iterators and array::iterators? | I have been writing some functions that take a template called It, which should be an iterator. Then I use the It::value_type for some functionality. This has been working for most containers I have tried but fails for std::array. If I do use an std::array I get the error
error: ‘long unsigned int*’ is not a class, struct, or union type
So I see the problem, the iterator for the std::array is just a pointer, which makes sense to me. Therefore it has no ::value_type defined. But how can I make my templated code so that this works for std::array and std::vector, std::list etc?
I made a MWE, the function in it just a silly pathological example that shows my problem
#include <vector>
#include <iostream>
#include <array>
template <class It>
void print_accumulate(It first, It last) {
typename It::value_type result{}; // What do I write here??
while (first != last) {
result += *first;
++first;
}
std::cout << result << "\n";
}
int main() {
std::vector<size_t> v = {1, 2, 3, 4, 5}; /* Replacing with std::array<size_t, 5> gives error */
print_accumulate(v.begin(), v.end());
}
The above works just fine for just about every container I've tried, vector, list, set etc. However, when I try to run the code by replacing the std::vector<size_t> with std::array<size_t, 5>, i get the error message I gave.
Thanks in advance!
| Use iterator_traits
template <class It>
void print_accumulate(It first, It last) {
typename std::iterator_traits<It>::value_type result{}; // use iterator_traits
while (first != last) {
result += *first;
++first;
}
std::cout << result << "\n";
}
|
69,783,060 | 69,783,115 | Getting a warning when I use a class within a class in C++ | #include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class Course{
public:
string name;
int pars[];
Course();
};
class Runs{
public:
Course course; <- Error
int scores[];
Runs();
};
I am trying to use the classes to read lines from a badly formatted file. Why can't I use a class within a class?
| int pars[];
This is not a valid C++ class member declaration. In standard C++ the sizes of all arrays must be defined at compile-time as a constant, fixed size.
Your compiler implements a non-standard C++ language extension that allows this class member declaration in order to use it in a particular way. However you cannot use that class, any more, as a member of another class, due to the technical way in which this non-standard C++ language extension works.
You will need to remove this class member. Perhaps use a std::vector in its place, which is basically an array whose size can be changed at runtime. See your C++ textbook for a more complete discussion of vectors, how they work, and how to use them.
|
69,783,203 | 69,786,586 | Examples of when PUBLIC/PRIVATE/INTERFACE should be used in cmake | I was reading about the cmake keywords PUBLIC, PRIVATE, INTERFACE and came across this paragraph here in the cmake docs.
Generally, a dependency should be specified in a use of target_link_libraries() with the PRIVATE keyword if it is used by only the implementation of a library, and not in the header files. If a dependency is additionally used in the header files of a library (e.g. for class inheritance), then it should be specified as a PUBLIC dependency. A dependency which is not used by the implementation of a library, but only by its headers should be specified as an INTERFACE dependency.
I understand how your choice between these three keywords affects the behavior of target_link_libraries and target_include_directories but I don't understand the distinction between the three cases explained in this paragraph. Could someone provide a toy example of
using a dependency in the implementation of a library, but not in the header files (PRIVATE)
using a dependency in the implementation of a library and also in the header files (PUBLIC)
using a dependency in the header files of a library but not in the implementation (INTERFACE)
| Let's first deal with PUBLIC and PRIVATE:
Let's say you're writing a tool with a Qt GUI. You this GUI is supposed to allow you to dynamically add elements to the GUI using plugins. Furthermore the user should be able to activate and deactivate the plugins via settings and the same plugins need to be activated on future starts of the program.
Your library therefore provides 2 functionalities:
Creating Qt GUI elements. You need to use types from Qt in your public headers, so you add Qt includes to those headers. Every library needs to have access to the Qt headers, so you link Qt PUBLICly
For persisting the plugin settings you choose Boost.JSON to store the settings in a file at a given location on the file system. The user of your libary won't actually deal with the JSON parsing/writing themselves, so you don't include any boost headers in your public headers and link Boost.JSON PRIVATEly.
INTERFACE visibility
You'll rarely use this visibility. Usually you'll need access to the headers, ect. in your own libary.
Header only libraries are one scenario where INTERFACE visibility is used though. Header only libraries won't actually result in a target being created in your build system and they cannot be built separately. The CMake target itself is just a convenient way making headers and dependent libraries available via target_link_libraries.
Another scenario where INTERFACE visibility is used are imported targets. Those aren't compiled as part of your project either. They just contain information about an library that's already built. For imported targets you can only use INTERFACE visibility.
|
69,783,463 | 69,783,499 | OpenCV Both RANSAC and LMeDS making an essential matrix of size 0 | I was trying to use the findEssentialMat function to produce an essential matrix and kept getting an empty matrix, even with very low probability and high threshold values. I made reproduceable code that tries to compute the essential matrix from a still image, and I still get no essential matrix. I'm not sure why this is happening.
Code:
int main(int argc, char** argv) {
Mat in = imread("test.jpg", IMREAD_GRAYSCALE);
std::vector<KeyPoint> keypoints;
std::vector<Point2f> points;
std::vector<Point2f> prevPoints;
std::vector<uchar> status;
points = featureDetection(in, keypoints, 30);
prevPoints = std::vector<Point2f>(points);
double focal = 0;
Point2d opticalCenter(in.rows / 2, in.cols / 2);
// Track features
featureTracking(in, in, points, prevPoints, status);
// FIXME RANSAC algorithm not working. Try LMEDS?
Mat E, mask;
E = findEssentialMat(points, prevPoints, focal, opticalCenter, RANSAC, 0.001, 100.0, mask);
Mat R, t;
if(E.size().area() == 0) {
std::cout << mask.size().area() << " points, essential matrix is empty\n";
} else {
recoverPose(E, points, prevPoints, R, t, focal, opticalCenter, mask);
}
// Draw tracked features (this frame)
for(int i = 0; i < prevPoints.size(); i++) {
// Tracking lines
line(in, points[i], prevPoints[i], Scalar(0, 100, 0), 5, LineTypes::LINE_4);
}
// Show output
imshow("Data", in);
char c = waitKey(0);
imwrite("out.jpg", in);
std::vector<Point2f> featureDetection(const Mat& imgIn, std::vector<KeyPoint>& pointsOut, int threshold) {
bool nonmaxSuppression = true;
FAST(imgIn, pointsOut, threshold, nonmaxSuppression);
std::vector<Point2f> points(0);
for(KeyPoint p : pointsOut) {
points.push_back(p.pt);
}
return points;
}
void featureTracking(const Mat& img_1, const Mat& img_2, std::vector<Point2f>& points1, std::vector<Point2f>& points2, std::vector<uchar>& status) {
//this function automatically gets rid of points for which tracking fails
std::vector<float> err;
Size winSize=Size(21,21);
TermCriteria termcrit=TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01);
cv::calcOpticalFlowPyrLK(img_1, img_2, points1, points2, status, err, winSize, 3, termcrit, 0, 0.001);
//getting rid of points for which the KLT tracking failed or those who have gone outside the frame
int indexCorrection = 0;
for( int i=0; i<status.size(); i++) {
Point2f pt = points2.at(i- indexCorrection);
if ((status.at(i) == 0)||(pt.x<0)||(pt.y<0)) {
if((pt.x<0)||(pt.y<0)) {
status.at(i) = 0;
}
points1.erase (points1.begin() + i - indexCorrection);
points2.erase (points2.begin() + i - indexCorrection);
indexCorrection++;
}
}
}
Input:
Output (Markers denoted by *):
I'm using OpenCV 4.5.4 built for MinGW
| It looks like the findEssentialMat function does not work with a focal length of 0, setting it to 1 fixed the issue!
|
69,783,903 | 69,783,972 | How to calculate the average score in struct function of C++? | This is the question that I was aasigned.
https://i.stack.imgur.com/efRFk.png
And this is my coding. This is my first time asking question here so I dont really know how to paste my coding here.
https://i.stack.imgur.com/QCOBG.png
I really hope someone can help me out. Thank you.
| You can use the below shown program as a starting point(reference). In your program you were creating an ordinary(nonmember) double named average while according to the assignment average should be a data member as shown below. Second, there is no need to create a separate variable called sum because you can use variable average to sum all the test scores and then divide average by 3 which is also shown below.
#include <iostream>
struct Result
{
public:
//this takes input from user
void takeTestInput()
{
for(int i = 0; i < sizeof(test)/sizeof(int); ++i)
{
std::cout<<"Input#"<<i+1<<": ";
std::cin >> test[i];//take the input and put into test[i]
}
}
void calculateAverage()
{
for(int i = 0; i < sizeof(test)/sizeof(int); ++i)
{
average+=test[i];
}
average = average/3;
}
void printAverage()
{
std::cout<<average;
}
private:
int test[3];
double average; //data member called average
};
int main()
{
Result student1;
//take input for student1
student1.takeTestInput();
//calculate average for student1
student1.calculateAverage();
//check if the average calculated above is correct by printing out the average for student1
student1.printAverage();
return 0;
}
The output of the above program can be seen here.
|
69,784,052 | 69,784,273 | How to implement a variable multidimensional array using int** array = new int*[n];? | I tried this approach but I am getting error when I cout <<vararr[i][j]<<endl;
The problem I am trying to solve- hackerrank
my code-
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int* variablesizedarr(int size){
int* arr= new int [size];
for(int i=1;i<size;i++){
cin >>arr[i];
}
/*I believe the problem is when I return the arr array*/
return arr;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q,size;
cin >>n >>q;
int** vararr= new int* [n];
for(int i=0;i<n;i++){
cin >>size;
vararr[i]=variablesizedarr(size);
}
/*now printing the values to the console*/
for(int k=0;k<q;k++){
int i,j;
cin >>i>>j;
cout <<vararr[i][j]<<endl; /* difinetly an error in this line because that's what the compiler say*/
}
// deallocate the array
for(int i=0;i<n;i++){
delete [] vararr[i];
}
delete [] vararr;
return 0;
}
edit1: error I am getting-
Compiler Message
Segmentation Fault
Error (stderr)
Reading symbols from Solution...done.
[New LWP 2655054]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./Solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x00000000004011f2 in main () at Solution.cpp:32
32 cout <<vararr[i][j]<<endl;
To enable execution of this file add
add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py
line to your configuration file "//.gdbinit".
To completely disable this security protection add
set auto-load safe-path /
line to your configuration file "//.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual. E.g., run from the shell:
info "(gdb)Auto-loading safe path"
I know I could do this the way other people have done it, but I was not going to learn like that. Any help is appreciated.
| Thanks to @nathanpearson I was able to find the error in
int* variablesizedarr(int size){
int* arr= new int [size];
for(int i=1;i<size;i++){
cin >>arr[i];
}
/*I believe the problem is when I return the arr array*/
return arr;
}
Here the initialization of i should be 0, not 1. I know it's a stupid mistake, but Hackerrank debugger is very bad in explaining the error so I was doubting my understanding. Anyway, this is another way to make a variable multidimensional array without using a vector.
Again, Thanks to Nathan for taking the time to understand my question.I really appreciate it.
|
69,784,441 | 69,784,456 | Why dereferencing is not required in pointer array? | In the code that is written below, when reading from cin, we should use the * operator before arr[i]. But without that, this code works perfectly. Why is that?
Similarly, we don't use * when we write to cout with pointer arrays. For instance, consider a multi-dimensional pointer array on the heap - cout << vararr[i][j] << endl; This also works.
int* variablesizedarr(int size){
int* arr = new int [size];
for(int i = 0;i < size; i++){
cin >> arr[i]; //shouldn't it be *arr[i] if the input is integers
}
return arr;
}
|
we should use the * operator before arr[i]
No, that'd be an error.
From cppreference:
The built-in subscript expression E1[E2] is exactly identical to the expression *(E1 + E2)except evaluation order (since C++17), that is, the pointer operand (which may be a result of array-to-pointer conversion, and which must point to an element of some array or one past the end) is adjusted to point to another element of the same array, following the rules of pointer arithmetics, and is then dereferenced.
so operator[] takes care of dereferencing.
|
69,784,664 | 69,784,673 | Remove format specifiers from printf |
I want to use printf to output a text.
If I want to print a text which has previously entered by the user and may contain a %, the output is a garbled mess.
This is propably due to % being a format specifier in printf, but no value/argument is given.
For example:
std::string inputString = "% Test";
printf(inputString.c_str());
Output: 6.698271e-308st
Desired output would be: % Test
Is there an elegant way to avoid this?
Entering %% instead of % works, but it's obviously not very user-friendly.
The only other way I see is modifying the input string to automatically replace every single % with %%. But is this the way to go?
I'm specifically want/need to use printf, using cout is not possible
| prints always takes a format string as the first parameter. You cannot change that.
However, you can use it to specify that it should just print a string passed as the second argument as is.
std::string inputString = "% Test";
printf("%s", inputString.c_str());
Note that, while there is no restriction of what char array you can pass as the format string, you should not use strings provided by a user, even if you don't expect any funny characters in it.
It creates an exploitable vulnerability.
Usually, it's the best to use a string literal. It allows the compiler to warn you if you pass incorrect types of arguments. (Compilers don't have to check that but they often do.)
Maybe I should mention that printf is a C function.
While using it in C++ program is entirely fine, you could consider switching to C++ style streams from the header <iostream>.
They have advantages and disadvantages but I think in your case they would be easier to use, especially that they support std::string.
#include <iostream>
#include <string>
int main(){
std::string inputString = "% Test";
std::cout << inputString;
}
|
69,784,861 | 69,784,909 | If a string is an array of char, how do you convert it into an array of interger | I kept getting an error with this loop. If there are something i missed, please help. Thank You!
int main(){
string hasil;
int cod[5];
hasil = "99999";
for(int i = 0; i < 5; i++){
cod[i] = stoi(hasil[i]);
}
for(int i = 0; i < 5; i++){
cout << cod[i] + 1;
}
| std::stoi() takes a std::string, not a char. But std::string does not have a constructor that takes only a single char, which is why your code fails to compile.
Try one of these alternatives instead:
cod[i] = stoi(string(1, hasil[i]));
cod[i] = stoi(string(&hasil[i], 1));
string s;
s = hasil[i];
cod[i] = stoi(s);
char arr[2] = {hasil[i], '\0'};
cod[i] = stoi(arr);
|
69,785,049 | 69,786,799 | Errors from valgrind (Treap) | Valgrind throws errors in this program when implementing the Treap data structure. Can't figure out how to fix this. Tried to write a destructor, nothing changed. The rest of the code is not included for simplicity. The error is in this part of the code.
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("input.txt");
ofstream out("output.txt");
class vertex{
public:
int x, y, label;
struct vertex *parent, *left, *right;
vertex() {}
};
typedef vertex *pvertex;
class decTree{
private:
int treeSize;
vertex *vertexs;
pvertex *ordered;
pvertex root;
int vertexCount;
public:
decTree(){
int a , b;
vertexCount = 0;
in >> treeSize;
vertexs = new vertex[treeSize];
ordered = new pvertex[treeSize];
for (int i = 0; i < treeSize; i++ ){
in >> a >> b;
ordered[vertexCount] = vertexs + vertexCount;
vertexCount++;
}
}
};
int main(){
decTree *mytree = new decTree;
delete mytree;
}
///////////////////////////////////////////////////////////////////
==20464== HEAP SUMMARY:
==20464== in use at exit: 336 bytes in 2 blocks
==20464== total heap usage: 8 allocs, 6 frees, 90,408 bytes allocated
==20464==
==20464== 336 (56 direct, 280 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==20464== at 0x483E217: operator new[](unsigned long) (vg_replace_malloc.c:579)
==20464== by 0x1094A3: decTree::decTree() (in a.out)
==20464== by 0x1092AC: main (in a.out)
==20464==
==20464== LEAK SUMMARY:
==20464== definitely lost: 56 bytes in 1 blocks
==20464== indirectly lost: 280 bytes in 1 blocks
==20464== possibly lost: 0 bytes in 0 blocks
==20464== still reachable: 0 bytes in 0 blocks
==20464== suppressed: 0 bytes in 0 blocks
==20464==
==20464== For lists of detected and suppressed errors, rerun with: -s
==20464== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from
| Explicit use of operator new and delete (or new[] and delete[]) is consider a bad practice (since C++11 is in use). It is recommended to use RAII pattern.
In your case everything can be handled by use of std;:vector.
class decTree {
private:
int treeSize;
std::vector<vertex> vertexs;
std::vector<pvertex> ordered;
pvertex root;
int vertexCount;
public:
decTree(std::istream &in) {
int a, b;
vertexCount = 0;
in >> treeSize;
vertexs.resize(treeSize);
ordered.resize(treeSize);
for (int i = 0; i < treeSize; i++) {
in >> a >> b;
ordered[vertexCount] = &vertexs[vertexCount];
vertexCount++;
}
}
};
https://godbolt.org/z/co4jbcbvW
|
69,785,393 | 69,785,665 | Recursion Function over a Range of Inputs | A newbie learning C++ here. Im currently practicing the concept of calling a recursive function between a range of inputs by utilizing a for loop and am running into a "segmentation fault : 11" error.
The attempted code and the error Im facing is posted below. Now I know this error is most likely is a result of me not being comfortable with the concept of recursion so any insight would help greatly! (Note: This is not for homework, just a challenge problem I would like to understand better.)
Here is the math function i am trying to apply recursion to along with its base case and its range of inputs to test.
g(2x)= 2g(x)/ 1+g^2(x)
x in between the range of -1<= x <= 1;
x in between the range of -1<= x <= 1;
x incrementing 0.1
Base conditions:
tolerance= 10^-6
if (|x| < tolerance) return g(x)= x- x^3/6
Attempted Code
//Libraries
#include <iostream>
#include <cmath>
using namespace std;
//Function Prototypes
float recFunc(float);
int main(int argc, char** argv) {
//Call Recursive Function and Output Results
//from negative 1 to z
for (float x=-1.0; x<=0; x+=0.1f){
cout<<"X Value = "<<x<<" : g(2x) = "<<recFunc(x)<<endl;
}
//from 0 to 1
for (float x=0; x<1.1; x+=0.1f){
cout<<"X Value = "<<x<<" : g(2x) = "<<recFunc(x)<<endl;
}
return 0;
}
float recFunc(float x){
//Base condition
float tol= 1e-6f;
if(abs(x)< tol) return x-x*x*x/6;
//Recursive Call
float val= 2*(x-x*x*x/6)/1+(x-x*x*x/6)*(x-x*x*x/6);
return 2*recFunc(val);
}
| The posted math formula is basically
g(2 * x) = F(g(x))
It can be rewritten as
g(x) = F(g( x / 2 ))
So, to fix recFunc, you have to:
Evaluate g at x/2. This is the recursive call to recFunc, but with x / 2 as argument. Assign the returned value to variable, like val.
Return F(val). Meaning, apply the posted formula to value calculated in the previous point.
|
69,785,567 | 69,785,632 | Why is a qualified name required after the second level of inheritance? | I ran into a problem, that I somehow managed to solve, but still would like to understand the language and the reasoning behind it. I have the following system of three classes:
File class_a.hpp
#pragma once
class A
{
public:
A();
};
File class_b.hpp
#pragma once
#include "class_a.hpp"
class B : A
{
public:
B() : A() {}
virtual double do_something(A &with_object) const;
};
File class_c.hpp
#pragma once
#include "class_b.hpp"
class C : B
{
public:
C() : B() {}
double do_something(::A &with_object) const; // but differently than class B
};
Now if I was not to use the fully qualified name for the type A in the C's do_something() method, I'd get the following error still in editor:
type "A::A" (declared at line 27 of "class_a.hpp") is inaccessible C/C++(265)
What could be possible causing any ambiguity in this case? I certainly haven't redefined or used the name A as an identifier. Is there something happening in the background that makes use of the class name?
Also is the override of the do_something() method guaranteed to work this way, or is qualifying the type A in the B's method also required?
Any advice and/or pointers are also greatly appreciated!
| Among other things that are inherited, there are injected-class-names. You can think of them as of hidden type aliases: class A has something like using A = A; in it, pointing to itself.
And remember that class inheritance is private by default.
Since B inherits from A privately, C can't access the contents of A, which includes A's injected-class-name.
Also is the override of the do_something() method guaranteed to work this way, or is qualifying the type A in the B's method also required?
Yes, the override in B is valid. Since B inherits from A directly, it can access all its contents, regardless of whether the inheritance is private or not.
Your code is similar to following. I replaced the injected-class-name with an actual type alias, and got the same behavior.
class A
{
public:
using A_type = A;
};
class B : A
{
public:
virtual double do_something(A_type &with_object) const;
};
class C : B
{
public:
double do_something(A_type &with_object) const;
};
|
69,786,470 | 69,786,523 | How to get frequency of std:vectors in C++? | I have 5 vectors. I want to check how many times these vectors exist. I used the following code to compare if 2 vectors are equal, but now I have more than 2 vectors. I want to compare all these 5 vectors together and count how many times each vector exists.
How can I do it?
The output should be:
(0,0,1,2,3,0,0,0) = 2 time(s)
(0,0,1,2,3,4,0,0) = 1 time(s)
(0,0,2,4,3,0,0,0) = 1 time(s)
(0,0,6,2,3,5,6,0) = 1 time(s)
Here is my code:
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
void checkVec(vector<int> v){
vector<int> v0;
if(v0 == v){
cout << "Equal\n";
}
else{
cout << "Not Equal\n";
}
}
int main(){
vector<int> v1={0,0,1,2,3,0,0,0};
vector<int> v2={0,0,1,2,3,4,0,0};
vector<int> v3={0,0,2,4,3,0,0,0};
vector<int> v4={0,0,1,2,3,0,0,0};
vector<int> v5={0,0,6,2,3,5,6,0};
checkVec(v1);
return 0;
}
| You can use std::map counting the number of occurences of each vector:
#include <map>
#include <vector>
#include <iostream>
using vec = std::vector<int>;
int main(){
vec v1={0,0,1,2,3,0,0,0};
vec v2={0,0,1,2,3,4,0,0};
vec v3={0,0,2,4,3,0,0,0};
vec v4={0,0,1,2,3,0,0,0};
vec v5={0,0,6,2,3,5,6,0};
std::map<vec,std::size_t> counter;
// Initializer list creates copies by default
// But you should not create vX variables anyway.
for(const auto& v: {v1,v2,v3,v4,v5}){
++counter[v];
}
std::cout<<"V1 is present " <<counter[v1]<<" times.\n";
return 0;
}
V1 is present 2 times.
|
69,786,627 | 69,789,266 | Get the last token out of wchar_t* | I have a wchar_t* in my C code, that contains URL in the following format:
https://example.com/test/...../abcde12345
I want to split it by the slashes, and get only the last token (in that example, I want to get a new wchar_t* that contains "abcde12345").
How can I do it?
Thank you?
| In C, you can use wcsrchr to find the last occurence of /:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
int main(void){
wchar_t *some_string = L"abc/def/ghi";
wchar_t *last_token = NULL;
wchar_t *temp = wcsrchr(some_string, L'/');
if(temp){
temp++;
last_token = malloc((wcslen(temp) + 1) * sizeof(wchar_t));
wcscpy(last_token, temp);
}
if(last_token){
wprintf(L"Last token: %s", last_token);
}else{
wprintf(L"No / found");
}
}
|
69,786,633 | 69,786,995 | How to colorize console background with COLOREF RGB code? | Here I ask you : How are we supposed to colorize the console background with only the COLOREF datatype as a parameter?
The most common way of colorizing background is by using windows header function system("color --")
However, this way is not possible, and I am tasked to find out if we can colorize the console background using only the COLOREF datatype.
I did some research, and what I came across was SetConsoleAttribute(), and the windows header function system("color --").
This is what I expect my code to be:
COLOREF data = RGB(255, 0, 0);//red, basically
SetConsoleBackground(HDC *console, data);
Any way of doing this? Thanks in advance.
| [NEW ANSWER (edit)]
So @IInspectable pointed out the the console now supports 24-bit full rgb colors so i did some research and managed to make it work.
This is how i solved it:
#include <Windows.h>
#include <string>
struct Color
{
int r;
int g;
int b;
};
void SetBackgroundColor(const Color& aColor)
{
std::string modifier = "\x1b[48;2;" + std::to_string(aColor.r) + ";" + std::to_string(aColor.g) + ";" + std::to_string(aColor.b) + "m";
printf(modifier.c_str());
}
void SetForegroundColor(const Color& aColor)
{
std::string modifier = "\x1b[38;2;" + std::to_string(aColor.r) + ";" + std::to_string(aColor.g) + ";" + std::to_string(aColor.b) + "m";
printf(modifier.c_str());
}
int main()
{
// Set output mode to handle virtual terminal sequences
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwMode = 0;
GetConsoleMode(hOut, &dwMode);
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hOut, dwMode);
SetForegroundColor({ 100,100,20 });
SetBackgroundColor({ 50,100,10 });
printf("Hello World\n");
system("pause");
}
[OLD ANSWER]
The console only supports 256 different color combinations defined with a WORD which is 8 bits long. The background color is stored in the 4 higher bits. This means the console only has support for 16 different colors:
enum class Color : int
{
Black = 0,
DarkBlue = 1,
DarkGreen = 2,
DarkCyan = 3,
DarkRed = 4,
DarkPurple = 5,
DarkYellow = 6,
DarkWhite = 7,
Gray = 8,
Blue = 9,
Green = 10,
Cyan = 11,
Red = 12,
Purple = 13,
Yellow = 14,
White = 15,
};
To set the background color of the typed characters, you could do:
void SetWriteColor(const Color& aColor)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, static_cast<WORD>(aColor) << 4);
}
|
69,786,737 | 69,786,982 | Confused why FD_SET crashes with a large value like 536872413? | there is a crash stack in iOS14.2 (arm64):
* thread #1245, queue = 'com.xxx.xxx.sdt (QOS: UNSPECIFIED)', stop reason = EXC_BAD_ACCESS (code=1, address=0x175ce5548)
frame #0: 0x000000010bac2548 XXXApp`RecvWithinTime(int, char*, unsigned long, sockaddr*, unsigned int*, unsigned int, unsigned int) [inlined] __darwin_fd_set(_fd=536872413, _p=0x0000000171ce5490) at _fd_def.h:93:56
frame #1: 0x000000010bac24d4 XXXApp`RecvWithinTime(_fd=536872413, _buf="", _buf_n=65536, _addr=0x0000000171ce5788, _len=0x0000000171ce5780, _sec=3, _usec=0) at dnsquery.cc:556
frame #2: 0x000000010babecc4 XXXApp`try_socket_gethostbyname(_host="xx.xxx.com", _ipinfo=0x0000000171d05f44, _timeout=3000, _dnsserver="2408:8000:1010:1::8", _qtype=1, _socket_errno=0x0000000171d05d98, _interface_name="") at dnsquery.cc:321:30
source code of RecvWithinTime and __darwin_fd_set are:
int RecvWithinTime(int _fd, char* _buf, size_t _buf_n, struct sockaddr* _addr, socklen_t* _len, unsigned int _sec, unsigned _usec) {
struct timeval tv;
fd_set readfds, exceptfds;
int n = 0;
FD_ZERO(&readfds);
FD_SET(_fd, &readfds); // line 554, why crash not happened here ?
FD_ZERO(&exceptfds); // line 555
FD_SET(_fd, &exceptfds); // line 556, crashed here
...
}
__header_always_inline void
__darwin_fd_set(int _fd, struct fd_set *const _p)
{
if (__darwin_check_fd_set(_fd, (const void *) _p)) {
// crash here: crash address 0x175ce5548 = (unsigned long)_fd / __DARWIN_NFDBITS + (&exceptfds) = 536872413/32 * 4 + 0x0000000171ce5490
(_p->fds_bits[(unsigned long)_fd / __DARWIN_NFDBITS] |= ((__int32_t)(((unsigned long)1) << ((unsigned long)_fd % __DARWIN_NFDBITS))));
}
}
_fd is initialized with -1:
#define INVALID_SOCKET -1
SOCKET _fd = INVALID_SOCKET;
as you can see,in the crash stack,the value of _fd is 536872413, and it's the reason why crash happened.
Another interesting thing is why crash not happened in line 554 but line 556 with the same value of _fd(536872413).
| Given the additional information, you cannot call FD_SET with an invalid file descriptor. -1 is not a valid file descriptor (no open file will ever have that value).
An fd_set is a fixed size buffer. Executing FD_CLR() or FD_SET() with
a value of fd that is negative or is equal to or larger than
FD_SETSIZE will result in undefined behavior. Moreover, POSIX requires
fd to be a valid file descriptor.
|
69,787,525 | 69,788,188 | How to insert multiple variables inside c++ std::system()? | I'm trying to add multiple variables inside the std::system function. By using .c_str on the end it only accepts one variable.
system(("riverctl map normal " + modkey + " " + i + " set-focused-tags " + decimal).c_str);
| This code
"riverctl map normal " + modkey
calls operator+ on two things: "riverctl map normal " and modkey. Which operator+ this is depends on the types of the two operands of +.
You want it to call operator+ which concatenates strings; if any of the two first operands is a string (std::string), the first + will do the right thing, and all the following + will do too (because the result of the first + would be std::string).
If modkey is an integer (any type of integer, including char), this + will do the wrong thing (unwanted pointer arithmetic). To fix, convert any of the first two operands to a string. If modkey is an integer, you have to use std::to_string on it anyway, so converting the first operand is not necessary. But for consistency (i.e. to stop worrying what would happen if you changed the format of your message), you might want to convert even the first one:
// minimal required change
system(("riverctl map normal " +
std::to_string(modkey) + " " +
std::to_string(i) + " set-focused-tags " +
std::to_string(decimal)).c_str());
// more robust code (C++14 and later)
system(("riverctl map normal "s +
std::to_string(modkey) + " " +
std::to_string(i) + " set-focused-tags " +
std::to_string(decimal)).c_str());
// more robust code (C++11)
system((std::string("riverctl map normal ") +
std::to_string(modkey) + " " +
std::to_string(i) + " set-focused-tags " +
std::to_string(decimal)).c_str());
If your command line is too complex, you might want to use a temporary stream for formatting; there are fewer surprises then:
std::ostringstream stream;
stream << "riverctl map normal " << modkey << " " << i << " set-focused-tags " << decimal;
system(stream.str().c_str());
|
69,787,557 | 69,788,799 | Time complexity of 3 nested loops with a condition | What is the time complexity (big O) of this function ? and how to calculate it ?
I think it's O(N^3) but am not sure.
int DAA(int n){
int i, j, k, x = 0;
for(i=1; i <= n; i++){
for(j=1; j <= i*i; j++){
if(j % i == 0){
for(k=1; k <= j; k++){
x += 10;
}
}
}
}
return x;
}
| The complexity is O(n^4)
But not because you blindly drop unused iteration.
it's because when you consider all instruction, O(n + n^3 + n^4) = O(n^4)
int DAA(int n){
int x = 0;
for(int i=1; i <= n; i++) // O(n)
for(int j=1; j <= i*i; j++) // O(1+2+...n^2) = O(n^3)
if(j % i == 0) // O(n^3) same as loop j
for(int k=1; k <= j; k++) // O(n^4), see below
x += 10; // O(n^4) same as loop k
return x;
}
Complexity of conditioned inner loop
the loop k only execute when j%i==0, i.e. {i, i*2, i*3 ... i*i}
so for the case the inner-most loop execute, the algorithm is effectively
int DAA(int n){
int x = 0;
for(int i=1; i <= n; i++) // O(n)
for(int t=1; t <= i; t++) // O(1+2+...+n) = O(n^2)
for(int k=1; k <= t*i; k++) // O(n^4)
x += 10;
return x;
}
Why simply drop unused iteration not work?
let's say it's now
int DAA(int n){
int x = 0;
for(int i=1; i <= n; i++) // O(n)
for(int j=1; j <= i*i; j++) // O(1+2+...+n^2) = O(n^3)
if(j == i)
for(int k=1; k <= j; k++)
x += 10; // oops! this only run O(n^2) time
return x;
}
// if(j==i*log(n)) also cause loop k becomes O((n^2)log(n))
// or, well, if(false) :P
Although the innermost instruction only run O(n^2) time. The program actually do if(j==i)(and j++, j<=i*i) O(n^3) time, which make the whole algorithm O(n^3)
|
69,787,566 | 69,787,911 | Making a factorial program faster? | I've been trying to submit this to a website with programming lessons, but the judge keeps telling me that this program takes too long to execute :/
Problem Statement:
Write a program that reads a non-negative integer n from the standard input, will count the digit of tens and the digit of ones in the decimal notation of n!, and will write the result to the standard output. In the first line of input there is one integer D (1≤D≤30), denoting the number of cases to be considered. For each case of entry. your program should print exactly two digits on a separate line (separated by a single space): the tens digit and the ones digit of n! in the decimal system.
Input/Output:
Input
Output
2
1
0 1
4
2 4
#include <iostream>
using namespace std;
int d,n;
int main()
{
cin>>d;
for(int i=0; i<d; i++)
{
cin>>n;
int silnia = 1;
for(int j=n; j>1; j--)
{
silnia=silnia*j;
}
if(silnia == 1) cout<<0<<" "<<silnia<<"\n";
else cout<<(silnia/10)%10<<" "<<silnia%10<<"\n";
}
return 0;
}
| Since only the last 2 digits of n! are needed, any n >= 10** will have a n! with 00 as the last 2 digits.
A short-cut is to test n: This takes the problem from O(n) to O(1).
int factorial = 0;
if (n < 10) {
int factorial = 1;
for(int j=n; j>1; j--)
{
factorial *= j;
}
factorial %= 100;
}
Or use a look-up table for n in the [0...10) range to drop the for loop.
---
** 10_or_more! has a 2 * 5 * 10 * other factors in it. All these factorials then end with 00.
|
69,787,667 | 70,036,610 | Is generating unique ID from template template parameters UB? | I am trying to generate unique IDs from template template parameters. I tried this function
inline size_t g_id = 1;
template<template<typename> typename T>
inline size_t GetID()
{
static size_t id = g_id++;
return id;
}
it works fine until used with alias templates
template<template<typename> typename T>
inline void print()
{
std::cout << GetID<T>() << "\n";
}
template<typename T>
struct S {};
struct W1 { template<typename A> using type = S<A>; };
struct W2 { template<typename A> using type = S<A>; };
int main()
{
print<S>();
print<W1::type>();
print<W2::type>();
std::cin.get();
}
MSVC
1
2
3
clang
1
2
3
gcc
1
1
1
Is any compiler correct here or is there UB somewhere?
Update
After reading some of the material linked from Davis Herring`s comment CG1286, an alias template does not need to have the same template name as the underlying template. To me this seems like it could go both ways so are all compilers compliant here?
With that I have come up with a different way to generate IDs from template template parameters which should avoid this problem but has some compromises. Requires that you specialize the template with a Tag type and create a static method which retrieves your ID.
Implementation
inline size_t g_id = 1;
template<typename T>
inline size_t GenerateID()
{
static size_t id = g_id++;
return id;
}
struct Tag {};
template<template<typename...> typename T, typename... Args, typename = decltype(sizeof(T<Args...>))>
inline size_t get_id_imp(int)
{
return T<Args...>::GetID();
}
template<template<typename...> typename T, typename... Args, std::enable_if_t<sizeof...(Args) < 16, bool> = true>//16 = max template args
inline size_t get_id_imp(...)
{
return get_id_imp<T, Args..., Tag>(0);
}
template<template<typename...> typename T, typename... Args, std::enable_if_t<sizeof...(Args) >= 16, bool > = true>
inline size_t get_id_imp(...)
{
return 0;
}
template<template<typename...> typename T>
inline size_t GetID()
{
return get_id_imp<T, Tag>(0);
}
Use
template<typename T>
struct X {};
template<> struct X<Tag> { static size_t GetID() { return GenerateID<X>(); } };
template<template<typename...> typename T>
inline void print()
{
std::cout << GetID<T>() << "\n";
}
| There is no UB here. The template GetID is instantiated once for each unique template argument, but GCC wrongly treats the alias templates as the template they alias itself, because they are equivalent here, as Davis Herring pointed out.
I think the simplest general solution is to pass the argument types in the alias templates through another alias template that makes them dependent names.
template<class Type> struct typeAlias { using AliasedType = Type; };
template<class Type> using AliasType = typename typeAlias<Type>::AliasedType;
template<typename T>
struct S {};
struct W1 { template<typename A> using type = S<AliasType<A>>; };
struct W2 { template<typename A> using type = S<AliasType<A>>; };
|
69,787,816 | 69,789,047 | Why is std::ifstream closing by itself? | I'm reading an ascii file this way:name1|name2|name3|name4|name5|name6|name7||||||||||name8|||name9
It consists in a bunch of names separated by the '|' char, some of the slots are empty. I'm using the following code to read the list of names:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
std::ifstream File;
File.open("File.txt");
if (!File.is_open())
return -1;
std::vector<std::string> Names;
char Buffer[0xff];
while (!File.getline(Buffer,16,'|').eof()) {
if (strlen(Buffer) == 0)
break;
Names.push_back(Buffer);
std::cout << strerror(File.rdstate()) << std::endl;
}
return 0;
}
It is working as it should, it reads a name each time, but for some reason if it hits the char count on the second argument of File.getline() and does not find the delimiting char, it closes itself. This is the console output I've got after running this code on a file with a big name:
File: File.txt
Ana|Bjarne Stroustrup|Alex
Console:
No error
No such file or directory
It reads the first name on the list successfully, but when it tries to read the second name, it doesn't hit the delimiting char, and for some reason it leads to the file closing by itself. I hope someone can explain to me why does this happen.
| The expression strerror(File.rdstate()) is not meaningful. The expression File.rdstate() returns an integer which represents the bits of the state flags of the stream. This is not an error code. However, the function strerror expects an error code.
Therefore, calling strerror(errno) or perror(nullptr) may be more meaningful, in general. But in this case, both just return or print "No Error".
In your question, you wrote:
It reads the first name on the list successfully, but when it tries to read the second name, it doesn't hit the delimiting char, and for some reason it leads to the file closing by itself. I hope someone can explain to me why does this happen.
The file does not close. The error message
No such file or directory
that you are receiving is misleading. It is a result of your incorrect usage of the function strerror, as described above.
What happens is that if getline is unable to read the deliminating character, it causes the failbit to be set. Due to the stream being in a failed state, the next function call of getline in the next loop iteration immediately fails without attempting to extract any characters. This causes the if statement
if (strlen(Buffer) == 0)
to be true, causing the loop to be aborted.
|
69,788,364 | 69,788,494 | C++ algorithm to sum contiguous blocks of integers | Given a block size N and a vector of integers of length k * N which can be viewed as k blocks of N integers, I want to create a new vector of length k whose elements are the sums of the blocks of the original vector.
E.g. block size 2, vector {1,2,3,4,5,6} would give a result of {3,7,11}.
E.g. block size 3, vector {0,0,0,1,1,1} would give a result of {0,3}.
A simple approach that works:
std::vector<int> sum_blocks(int block_size, const std::vector<int>& input){
std::vector<int> ret(input.size() / block_size, 0);
for (unsigned int i = 0; i < ret.size(); ++i)
{
for(unsigned int j=0; j < block_size; ++j)
ret[i] += input[block_size * i + j];
}
return ret;
}
However I'd be interested in knowing if there is a neater or more efficient way of doing this, possibly using the algorithm library.
| If you can use the range-v3 library, you could write the function like this:
namespace rv = ranges::views;
namespace rs = ranges;
auto sum_blocks(int block_size, std::vector<int> const & input)
{
return input
| rv::chunk(block_size)
| rv::transform([](auto const & block) {
return rs::accumulate(block, 0);
})
| rs::to<std::vector<int>>;
}
which is quite self-explanatory, and avoids doing any arithmetic like block_size * i + j, which is error prone.
demo.
|
69,788,990 | 69,789,104 | How to add a myOwn-background image to QPlainTextEdit? | For example, if you create a simple plaintextedit, the background is just white. How do I change white background with my own image?
| In design edit, you can set the styleSheet in properties of QWidget. In c++ code you can set the background using QSS, for example, setting
background-image: URL("path/image.png");:
myWidget->setStyleSheet("background-image: URL('path/image.png')");
|
69,789,272 | 69,789,388 | Why is the code after my for loop being ignored? | I don't think you'll need to know the context of the problem to answer this question, but I'll give it just in case.
-In the past N weeks, we've measured the amount of rainfall every day, and noted it down for each day of the week. Return the number of the first week of the two week period where there were the most days without rain.
The code gives no warnings or errors, and if I try to print dryestweeks inside the second for loop, then it returns the correct answer. However, all of the code after the second for loop seems to be getting ignored, and I'm getting Process returned -1073741819 (0xC0000005). The issue has to lie in the 2nd for loop, because if I comment it out then both "test2" and dryestweeks get printed, and the program returns 0.
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main() {
int weeks;
cin >> weeks;
vector<int> v[weeks];
for (int i = 0;i < weeks; i++) {
int a, b, c, d, e, f, g;
cin >> a >> b >> c >> d >> e >> f >> g;
v[i].push_back(a);
v[i].push_back(b);
v[i].push_back(c);
v[i].push_back(d);
v[i].push_back(e);
v[i].push_back(f);
v[i].push_back(g);
}
int mostdrydays = 0;
int dryestweeks = 0;
for (int i = 0; i < weeks; i++) {
int weeklydrydays = count(v[i].begin(), v[i].end(), 0);
int nextweekdrydays = count(v[i+1].begin(), v[i+1].end(), 0);
int biweeklydrydays=weeklydrydays+nextweekdrydays;
if (biweeklydrydays > mostdrydays) {
mostdrydays = biweeklydrydays;
dryestweeks = i + 1;
}
}
cout << "test2" << endl;
cout << dryestweeks << endl;
return 0;
}
An example of an input would be:
6
5 10 15 20 25 30 35
0 2 0 0 0 0 0
0 0 0 1 0 3 0
0 1 2 3 4 5 6
5 1 0 0 2 1 0
0 0 0 0 0 0 0
The program should print "2" with the above input.
| The second loop has an overflow.
You first defined v[weeks] and then the second loop goes from [0, weeks[ but you are retrieving the next week with v[i + 1]. I don't know exactly what are you are trying to achieve, but if you do
for(int i = 0; i < weeks - 1; i++)
{
...
}
it executes properly.
|
69,789,570 | 69,793,968 | WebAssembly: thread-safety and C/C++ local variables | I'm trying to understand the WebAssembly memory model, specially from the perspective of: what kind of risks I'm exposed to when sharing linear memory between WebAssembly instances? The basic memory model that all C/C++ => wasm tutorials gives us is as follow (the stack starts as __heap_base - 1 and grows downwards):
+-----------------------------------------------+
| ? | static data | stack | heap |
+-----------------------------------------------+
^ ^ ^ ^ ^
| | | | |
0 __global_base __data_end __heap_base MAX_MEMORY
But the following fact surprised me. From https://webassembly.org/docs/security/:
Local variables with unclear static scope (e.g. are used by the address-of operator, or are of type struct and returned by value) are stored in a separate user-addressable stack in linear memory at compile time. This is an isolated memory region with fixed maximum size that is zero initialized by default.
and from https://github.com/WebAssembly/design/blob/main/Rationale.md#locals:
C/C++ makes it possible to take the address of a function's local values and pass this pointer to callees or to other threads. Since WebAssembly's local variables are outside the address space, C/C++ compilers implement address-taken variables by creating a separate stack data structure within linear memory. This stack is sometimes called the "aliased" stack, since it is used for variables which may be pointed to by pointers.
In other words, the stack defined from __heap_base - 1 to __data_end is an implementation artifact of C/C++ compiled modules. The "WASM stack" lives outside the linear memory. It just happens that, when you take the address of a local (for example), the compiler stores it in the "aliased stack" instead so there's an address to take.
Doesn't this behavior open the door to new kind of very dangerous data races in case of using shared memory?
Imagine a piece of code like this:
int calculation(int param1, int param2)
{
if (param1 == param2 * 2)
++param1;
else
++param2;
return param1 / 3 + param2;
}
Here, calculation is thread-safe. However, if I replace calculation by this equivalent form:
int calculation(int param1, int param2)
{
int* param = param1 == param2 * 2 ? ¶m1 : ¶m2;
++*param;
return param1 / 3 + param2;
}
Depending on compiler's output, calculation could no longer be thread-safe in case param1 and/or param2 are stored on the aliased-stack, which lives on the linear memory, which could be shared among other instances if shared memory is enabled by the --features=atomics,bulk-memory --shared-memory flags.
So, in which exact situations can the compiler decide to store a local variable on the aliased-stack?
EDIT: I did some tests to verify, and I would like to know if I'm right on this. I stored, on the heap, the memory addresses of the first, the half and the last local variables of a function that use 16 unsigned local variables, and I print them out from javascript, and the difference between the lowest stored address to __heap_base was 32*3 bytes + padding, and not 32*16 + padding, which means that only the three variables whose memory address was taken was stored on the aliased-stack. Of course, these tests are not thread-safe because I'm storing the addresses of locals outside the function, but it illustrates the point: if, on a re-entrant function, I'm temporarily taking the address of a local for implementation convenience, and, because of its complexity, the compiler isn't sure about what I'm trying to do, it could finally decide to store the local on the stack instead of changing its implementation, turning the function thread-unsafe.
| In a multi-threaded setup, each thread will get its own stack into the shared memory. The stack pointer (the creation of it seems to be done by LLVM createSyntheticSymbols) is placed into a WebAssembly global variable. Currently these globals are used as a thread-local storage. That means that each thread has its own global variable.
At the start of the WebAssembly instance, the main thread will have its own global variable pointing to the main thread stack into the shared memory. If you start another thread, during its startup time, its global variable will point to another place into the shared memory, where the stack for this thread is placed.
The allocation of the stack seems to be done by Emscripten __pthread_create_js if the caller does not supply its own pointer. The allocation of variables into the current stack is done here with stackAlloc where:
global.get __stack_pointer
is getting the current thread stack pointer, subtracts the needed bytes (the stack grows down), aligns it to 16 bytes and then remembers the new value back into the global. That is all thread safe, because the global is only accessible from the thread itself.
About the pointers, yes, the compiler will place the variables that are pointer-accessed into an explicit stack. Currently the WebAssembly stack is not "walkable", but there is a proposal to make it so. An explicit stack is additionally used by many implementations, to gain more fine-grained control over the stack usage (variables, structures and so on).
All of this "stuff" SHOULD (RFC 2119) be transparent for the developers. Meaning, it appears to just work.
Based on your comments: the WebAssembly standard at this time deals with the data races by the use of atomic instructions. The ordering of access for them is sequentially consistent. In the case of multi-threading, clearly the memory allocator MUST be thread safe. The use of the explicit thread dedicated stack by itself does not have to be (using globals is enough, as written up), because the stack memory is only managed by the thread itself. Check the threads proposal for the atomic instructions and the implementation status. It is allowed to use atomic instructions in unshared memory as well.
Some implementations MAY lock the whole memory when they do non-atomic access as well as for the atomic access. That is at least for the reason that the specification does not forbid higher memory access guaranties. That means that even if you create a race at some memory address, you will not manage to read inconsistent/teared values. However, this is just a possibility that SHOULD NOT be relied upon.
|
69,789,646 | 69,789,827 | Generic task wrapper | Let's say this is how I dispatch a task to the gui thread:
void DispatchToGuiThread(std::function<void(void)> task);
I want a generic GUIDispatchedTask class that turns this:
// foo takes some arguments and must be run in the gui thread
auto guiDispatchedTask = [] (A a, B b, C c, D d) {
DispatchToGuiThread(
[a = a, b = b, c = c] {
foo(a, b, c);
}
);
};
to this:
auto guiDispatchedTask = GUIDispatchedTask{ foo };
I don't want to repeat the arguments of foo like GUIDispatchedTask<A, B, C> because foo is likely going to be a lambda and repeating the arguments is tedious. I could not make that work.
| You can also do it with generic lambda.
template<typename F>
auto GUIDispatchedTask(F f){
return [=](auto&&... args){
DispatchToGuiThread([=]{f(args...);});
};
}
|
69,789,768 | 69,790,452 | atmega328 ctc mode timer | So i wanted to make a timer on the atmega328p µC using the CTC Modus. The idea was, that every 10milliseconds when the interrupt function is called , in that function i schould increase a variable millisekunden by 10. and once it reaches 1000 it schould be printed out .
The datasheet can be found here: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf With registers i can change the Mode to the CTC Mode and set up the right Prescaler on the timer.
It is a 16Mhz CPU. So the formula is : T_clock * Prescaler * OCR0A = time( unit is seconds)
So i calculated: (1/ 1610^6) * 1024 * x = 1010^-3(i wanted 10 milli seconds).
and x is then 155.
With the bits CS00 and CS02 i set up the prescaler to 1024. OCR0A was then set to 155 as the formula says. CTC mode was enabled by setting the BIT WGM01. And the last thing was that i increase the variable millisekunden in the interrupt function. For some reason it doesnt want to work. Can anyone pease help me?
#include "Arduino.h"
volatile unsigned long int millisekunden;
unsigned long int last_msg;
char buffer[128];
void setup() {
TCCR0A |= (1 << WGM01); // CTC Modus
TCCR0B |= (1 << CS02) | (1 << CS00); // Prescaler 1024
OCR0A = 155;
// Compare Interrupt
TIMSK0 |= (1 << OCIE0A);
Serial.begin(9600);
}
void loop() {
if (millisekunden - last_msg >= 1000) {
sprintf(buffer, "t=[%lu]", millisekunden);
Serial.println(buffer);
last_msg = millisekunden;
}
}
// Timer-Interrupt-Routine
ISR(TIMER0_COMPA_vect) {
millisekunden = millisekunden + 10;
}
| You forgot to globally enable interrupts. Add sei() at the end of setup()
|
69,789,787 | 69,789,916 | gdb catch throw, this thread | My binary (generated from C++) has two threads. When I care about exceptions, I care about exceptions thrown in one of them (the worker) but not the other.
Is there a way to tell gdb only to pay attention to one of the threads when using catch throw? The gdb manual (texinfo document) and googling suggest to me that this isn't possible, although I think I could request catching a specific type of exception, which hopefully only one of the threads would throw, using catch throw REGEXP.
|
Is there a way to tell gdb only to pay attention to one of the threads
The catch throw is really just a fancy way to set a breakpoint on __cxxabiv1::__cxa_throw (or similar), and you can make a breakpoint conditional on thread number, achieving the equivalent result.
Example:
#include <pthread.h>
#include <unistd.h>
void *fn(void *)
{
while(true) {
try {
throw 1;
} catch (...) {}
sleep(1);
}
return nullptr;
}
int main() {
pthread_t tid;
pthread_create(&tid, nullptr, fn, nullptr);
fn(nullptr);
return 0;
}
g++ -g -pthread t.cc
Using catch throw, you would get a breakpoint firing on the main and the second thread. But using break ... thread 2 you would only get the one breakpoint you care about:
gdb -q a.out
Reading symbols from a.out...
(gdb) start
Temporary breakpoint 1 at 0x11d6: file t.cc, line 17.
Starting program: /tmp/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Temporary breakpoint 1, main () at t.cc:17
17 pthread_create(&tid, nullptr, fn, nullptr);
(gdb) n
[New Thread 0x7ffff7a4c640 (LWP 1225199)]
## Note: GDB refuses to set thread-specific breakpoint until the thread actually exists.
18 fn(nullptr);
(gdb) break __cxxabiv1::__cxa_throw thread 2
Breakpoint 2 at 0x7ffff7e40370: file ../../../../src/libstdc++-v3/libsupc++/eh_throw.cc, line 77.
(gdb) c
Continuing.
[Switching to Thread 0x7ffff7a4c640 (LWP 1225199)]
Thread 2 "a.out" hit Breakpoint 2, __cxxabiv1::__cxa_throw (obj=0x7ffff0000be0, tinfo=0x555555557dc8 <typeinfo for int@CXXABI_1.3>, dest=0x0) at ../../../../src/libstdc++-v3/libsupc++/eh_throw.cc:77
77 ../../../../src/libstdc++-v3/libsupc++/eh_throw.cc: No such file or directory.
(gdb) bt
#0 __cxxabiv1::__cxa_throw (obj=0x7ffff0000be0, tinfo=0x555555557dc8 <typeinfo for int@CXXABI_1.3>, dest=0x0) at ../../../../src/libstdc++-v3/libsupc++/eh_throw.cc:77
#1 0x00005555555551b5 in fn () at t.cc:8
#2 0x00007ffff7d7eeae in start_thread (arg=0x7ffff7a4c640) at pthread_create.c:463
#3 0x00007ffff7caea5f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95
(gdb) c
Continuing.
Thread 2 "a.out" hit Breakpoint 2, __cxxabiv1::__cxa_throw (obj=0x7ffff0000be0, tinfo=0x555555557dc8 <typeinfo for int@CXXABI_1.3>, dest=0x0) at ../../../../src/libstdc++-v3/libsupc++/eh_throw.cc:77
77 in ../../../../src/libstdc++-v3/libsupc++/eh_throw.cc
(gdb) bt
#0 __cxxabiv1::__cxa_throw (obj=0x7ffff0000be0, tinfo=0x555555557dc8 <typeinfo for int@CXXABI_1.3>, dest=0x0) at ../../../../src/libstdc++-v3/libsupc++/eh_throw.cc:77
#1 0x00005555555551b5 in fn () at t.cc:8
#2 0x00007ffff7d7eeae in start_thread (arg=0x7ffff7a4c640) at pthread_create.c:463
#3 0x00007ffff7caea5f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95
Voilà -- thread-specific catch throw equivalent.
|
69,790,128 | 69,790,207 | Unknown type name error when inserting into unordered_map | I have a single file called main.cpp where I am trying to declare an unordered_map as shown below.
std::unordered_map<std::string, std::set<int>> firstSets;
I then try to insert a new (key, value) pair into the map as follows.
std::string decl = "decl";
std::set<int> declFirstSet = {VOID_TOK, INT_TOK, FLOAT_TOK, BOOL_TOK};
firstSets[decl] = declFirstSet;
When I do this I get the following compiler error.
C++ requires a type specifier for all declarations
firstSets[decl] = declFirstSet;
size of array has non-integer type 'std::string' (aka 'basic_string')
firstSets[decl] = declFirstSet;
So it seems to think I am declaring 'firstSets' when I am actually tring to insert into it. And it seems to treat 'firstSets' as an array instead of an unordered_map. How do I fix this?
| Your std::make_pair is wrong. To get closer you need a std::set<int> instead of the std::set.
But what you really want is to just let to compiler make it for you:
firstSets.insert(std::make_pair(decl, declFirstSet));
or use an easier syntax:
firstSets[decl] = declFirstSet;
EDIT AFTER UNDERSTANDING THE PROBLEM
On the otherhand, you want firstSets to come with initial content you can reorder the declarations:
#include <set>
#include <string>
#include <unordered_map>
std::string decl{"decl"};
std::set<int> declFirstSet{1, 2, 3, 4};
std::unordered_map<std::string, std::set<int>> firstSets{{decl, declFirstSet}};
int main() {}
|
69,790,315 | 69,790,423 | Passing class member object - SFML draw() | It seems like a very weird situation. I just want to draw a sf::Text object that is handle outside the main loop (in another class).
I show you only the essential. This code works (it draws other things that are handle directly in the main) and so it compiles.
Main :
int main()
{
//we handle the creation of the window //
//...
//Example where the sf::Text is handle in the main (it works)
sf::Font font;
font.loadFromFile("arial.ttf");
sf::Text mainTxt("It works !!",font);
mainTxt.setPosition(sf::Vector2f(64,"It works !!"));
mainTxt.setCharacterSize(25);
mainTxt.setFillColor(sf::Color::Blue);
TextManager textManager(); //My class that don't work...
sf::Event event;
while (window.isOpen())
{
// We handle event (we don't care here)
// ...
window.draw(mainTxt); // it works
window.draw(textManager.getMyText()); // do nothing
window.display();
window.clear();
}
return 0;
}
TextManager header :
#ifndef TEXTMANAGER_H
#define TEXTMANAGER_H
#include <SFML/Graphics.hpp>
class TextManager
{
public:
TextManager();
virtual ~TextManager();
sf::Text getMyText();
private:
sf::Text myText;
};
#endif // TEXTMANAGER_H
TextManager cpp
#include "TextManager.h"
TextManager::TextManager()
{
sf::Font font;
font.loadFromFile("arial.ttf");
sf::Text myText("Not drawn on the screen :-(",font);
myText.setPosition(sf::Vector2f(164,0));
myText.setCharacterSize(25);
myText.setFillColor(sf::Color::Blue);
}
// in this example (that do not work) I do not change fspText. But, I want to update it at each call of the get function. So, it is not a constant class member.
sf::Text TextManager::getMyText() {
return myText;
}
TextManager::~TextManager()
{
//dtor
}
What I really do not understand, is the fact that with a custom class of mine, I can access a class member object with this type of getter. I also did some research, and I think It should return a copy of the sf::Text object.
I try lot of things, like return reference or const reference etc... I do not understand.
I hope my problem is well displayed.
Thank you for your help ;-)
And have a nice day !
| This
TextManager textManager(); //My class that don't work...
is function declaration, not construction of object.
Should be:
TextManager textManager; //My class that don't work...
By
sf::Text myText("Not drawn on the screen :-(",font);
you define a local variable called myText the same as your data member. So, myText returned by getMyText is just not affected.
Read the docs before coding:
It is important to note that the sf::Text instance doesn't copy the
font that it uses, it only keeps a reference to it. Thus, a sf::Font
must not be destructed while it is used by a sf::Text (i.e. never
write a function that uses a local sf::Font instance for creating a
text).
taken from SFML reference.
class TextManager
{
public:
TextManager();
virtual ~TextManager();
sf::Text& getMyText(); // <- pass by reference
private:
sf::Font myFont;
sf::Text myText;
};
and
TextManager::TextManager()
{
myFont.loadFromFile("arial.ttf");
myText.setString("Not drawn on the screen :-(");
myText.setFont(myFont);
myText.setPosition(sf::Vector2f(164,0));
myText.setCharacterSize(25);
myText.setFillColor(sf::Color::Blue);
}
might work.
|
69,791,065 | 69,791,686 | Constrainted auto std::convertible_to with initializer list | Hello stackoverflow people, I'm recently trying to learn c++20 constrainted auto as function parameters to reduce the boiler plate code.
I have a class template that is a wrapper for some data types, like std::int64_t, bool, double, std::string, will probably add more in the future, and it has a function that takes the data type and an overloaded function that takes a std::initializer_list<data_t> for array-ish manipulation.
template<typename data_t>
void set_data(data_t a_data)
template<typename data_t>
void set_data(std::initializer_list<data_t> a_dataList)
And these works fine if I call these setter functions directly.
In an api class that manages all these data, I have an exposed api that does basically same thing, I have this:
template<typename data_t>
void bind(Wrapper<data_t>& a_data, const std::convertible_to<data_t> auto a_value)
{
a_data.set_data(a_value);
}
template<typename data_t>
void bind(Wrapper<data_t>& a_data, const std::initializer_list<data_t> a_valueList)
{
a_data.set_data(a_value);
}
The first function works as intended, e.g I can pass any convertible data type to an wrapper of std::int64_t, but the latter one if I want to pass an initializer_list to it I have to explicitly convert the type to data_t like this
Wrapper<std::int64_t> iA;
bind(iA, 100); // works
iA.set_data(100) // works
bind(iA, {1,2,3,4,5}); // no
iA.set_data({1,2,3,4,5}); // works
bind(iA, {(std::int64_t)1, (std::int64_t)2, (std::int64_t)3, (std::int64_t)4});
// works
So my question finally came out: How do I implement something like std::convertible_to with std::initializer_list so I don't have to to type cast like above? Or is this doable at all?
| Your problem is C++ is deducing data_t using both 1st and 2nd arguments. If they disagree, no cookie.
template<typename data_t>
void bind(Wrapper<data_t>& a_data, std::type_identity_t<std::initializer_list<data_t>> a_valueList)
this blocks deduction in 2nd argument.
|
69,791,500 | 69,794,346 | How to convert float to fixed point (higher precision) in C++ | I'm trying to implement my own fixed point arithmatic in C++ to (later) do higher precision calculations. I was thinking something like
class FixedPoint
{
int intPart;
unsigned long long fracPart[some number];
}
I think it should work if I - for example for addition - first add two fracPart[some number]'s and if they overflow add 1 to fracPart[some number - 1] and so on.
But I'm stuck at converting a double "d" to a class like this. intPart = d of course works. Then doing
double Temp = d - intPart;
gives me the fractional part. But how do I correctly assign this to fracPart[0]? In decimal, if long long's had exactly 20 digits, I could just do Temp * 100000000000000000000, so that 0.14 becomes 14000000000000000000. But if in binary I take the mantissa-bits of d (53/54 bits), assign them to fracPart[0] (64 bits), add the hidden bit and shift this left by 13 (or 12 because of the hidden bit), the value is wrong. Nothing I found online so far is helpfull...
| Forget decimal. Use powers of 2. Your first fractional part should contain bits with the value 2^-1, 2^-2, ... 2^-64. The nice thing about floating point is that you can easily scale your values by powers of two. In other words, subtract the integer part, then multiply with 2^64, then take the next integer part, and so on. Something like this should work for you:
#include <cmath>
// using std::floor, std::ldexp
#include <cstdint>
// using std::int64_t, std::uint64_t
#include <cstdio>
// using std::printf
class FixedPoint
{
std::int64_t ipart;
std::uint64_t fpart[2];
public:
explicit FixedPoint(double f) noexcept
{
// rounded down so that the fractional part is always positive
ipart = std::floor(f);
f -= ipart;
for(std::uint64_t& fractional: fpart) {
f = std::ldexp(f, 64);
fractional = f;
f -= fractional;
}
}
operator double() const noexcept
{
double f = 0.;
for(int i = 1; i >= 0; --i) {
f += fpart[i];
f = std::ldexp(f, -64);
}
f += ipart;
return f;
}
};
int main()
{
double f1 = 123.4567;
FixedPoint p(f1);
double f2 = p;
std::printf("%g = %g\n", f1, f2);
}
Some final thoughts:
I hope you know that there are actual libraries to do this kind of stuff for you? I assume this is just an exercise to get your feet wet with floating point and fixed point. Otherwise cease and desist. ;-)
I switched to std::uint64_t because it is way more convenient to have a standard precision in your data type.
A downside in using uint64_t is that there is no fast double <-> uint64_t machine instruction in x86_64. Using uint32_t might actually be faster.
Using int for the integer part but a larger type for the fractional part is pointless. Due to alignment you just waste 32 bit of space in your struct that you could use for a larger range. Either switch both to 32 bit or use 64 bit for the integer part and keep the size of the fractional part (size of the whole array) a multiple of 64 bit, e.g. 2 x 32 bit
Note that std::frexp gives you the exponent of a floating point number and a normalized mantissa in the range [0.5, 1) (or zero). That would allow you to replace the integer part with the exponent for an arbitrarily large range without loss of precision. Of course at this point you are just reimplementing extended precision floating point in software.
|
69,791,947 | 72,644,910 | How to set environment variables in CMake so that they can be visible at build time? | On macOS 12, I tried to set some environment variables in CMakeLists.txt file like this.
# Add environment variables
set(ENV{VK_ICD_FILENAMES} /Users/username/VulkanSDK/macOS/share/vulkan/icd.d/MoltenVK_icd.json)
set(ENV{VK_LAYER_PATH} /Users/username/VulkanSDK/macOS/share/vulkan/explicit_layer.d)
But I quickly realize those environment variables only affects the current CMake instance. Basically, if I use message() in the same CMakeLists.txt file, CMake can print out the exact same value as I set. However, during build time, those variables do not exist and can't guide build phase.
My current solution is to generate Xcode project file and add those environment variables manually in Edit Scheme. But I want to learn CMake and do all the configurations in CMake. My question is if there is any way I can set environment variables in CMakeLists.txt file so that they at least persist during build phase?
| Maybe what you want is CMAKE_XCODE_ATTRIBUTE_<an-attribute>
https://cmake.org/cmake/help/latest/variable/CMAKE_XCODE_ATTRIBUTE_an-attribute.html
|
69,792,027 | 69,844,128 | CMake, Qt6 - module "QtQuick.Controls" is not installed | I'm currently working on learning QtQuick, and I've been running into a variety of issues, but this is the first one I've been unable to solve so far. For background, I'm using MVSC, Visual Studio 2019, CMake, and Qt6.
Upon running my very basic program, I'm getting the error module "QtQuick.Controls" is not installed on my import statement for QtQuick Controls in the main.qml file I made. The relevant part of the CMakeLists.txt file I'm using is:
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
find_package(Qt6 COMPONENTS Quick REQUIRED)
find_package(Qt6 COMPONENTS QuickControls2 REQUIRED)
find_package(Qt6 COMPONENTS Core REQUIRED)
find_package(Qt6 COMPONENTS Gui REQUIRED)
qt_add_executable(nameHere
"src/main.cpp"
"gui/main.qml"
)
target_link_libraries(nameHere PRIVATE Qt6::Quick Qt6::QuickControls2)
qt_import_plugins(nameHere QWindowsIntegrationPlugin )
Note: I've got some extra find packages in there from searching for solutions - removing or adding Gui or Core does not change the error
Upon checking the build folder, these dlls are there:
Qt6Gui
Qt6Core
Qt6Network
Qt6OpenGL
Qt6Qml
Qt6QmlModels
Qt6Quick
main.cpp looks like the following:
#include <QtQuick>
#include <QtQuickControls2>
int main(int argc, char* argv[])
{
QGuiApplication app(argc, argv);
QQuickView* view = new QQuickView;
view->setSource(QUrl::fromLocalFile("../../gui/main.qml"));
view->show();
return app.exec();
}
The contents of the main.qml file are
import QtQuick
import QtQuick.Controls
ApplicationWindow {
id: window
width: 400
height: 500
visible: true
}
Once again, the full error is:
/gui/main.qml:2:1: module "QtQuick.Controls" is not installed
import QtQuick.Controls
^
/gui/main.qml: module "QtQml.WorkerScript" is not installed
/gui/main.qml:2:1: module "QtQuick.Controls" is not installed
import QtQuick.Controls
^
/gui/main.qml: module "QtQml.WorkerScript" is not installed
Any help would be greatly appreciated!
Some further digging through my vcpkg files indicates there is in fact a Qt6QuickControls2.dll that isn't being placed into the build folder. I'm not a fan of just copy and pasting the file into the build folder. I'm not sure why all of the other Qt dlls are being placed into that folder by CMake, but not this specific dll. Is there something that I'm missing from my CMake file, or could this be a bug with how Qt is set up with CMake?
As well, just going ahead and copying the QuickControls2 dll file into the folder doesn't actually fix the problem, so I think there is something else going on here.
Well, in Qt6, QucikControls2 is included in QtQuick, so I'm not sure if it actually needs that extra dll? Not sure what's going on here, but I even went and ran windeployqt, and it says I've already got all of the needed runtime dependencies. Now I have no idea where this issue is coming from.
| Qml files should not be linked in the qt_add_executable. In Qt6, use
qt_add_qml_module(nameHere
URI gui
VERSION 1.0
QML_FILES gui/main.qml)
See the documentation here:
https://doc-snapshots.qt.io/qt6-dev/qt-add-qml-module.html
|
69,792,059 | 69,792,420 | WS_EX_LAYERED with SetParent() doesn't show the window | I have this one problem I just can't solve. I'm trying to make a window from my application that is transparent (using flags WS_EX_TRANSPARENT | WS_EX_LAYERED) a child to another window, which is not transparent.
When I don't use the call SetParent( my_window, target_parent_window ) with my_window having the WS_EX_LAYERED flag, the new child window won't be visible.
I found out that a manifest entry could help me, since having a child window with flag WS_EX_LAYERED is supported since Windows 8. I tried it without any success.
::SetWindowLongW( process_window, GWL_STYLE, WS_CLIPSIBLINGS | WS_POPUP | WS_VISIBLE );
::SetWindowLongW( process_window, GWL_EXSTYLE, WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW );
::SetWindowPos( process_window, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );
::ShowWindow( process_window, SW_SHOW );
::SetParent( process_window, new_parent_window); // if i skip this call the window will render perfectly
| https://learn.microsoft.com/en-us/windows/win32/winmsg/window-features
To create a layered window, specify the WS_EX_LAYERED extended window style when calling the CreateWindowEx function, or call the SetWindowLong function to set WS_EX_LAYERED after the window has been created. After the CreateWindowEx call, the layered window will not become visible until the SetLayeredWindowAttributes or UpdateLayeredWindow function has been called for this window.
|
69,792,106 | 69,792,285 | Confusing about char* in c++ | test code:
#include <iostream>
using namespace std;
int main()
{
const char* b="str";
cout << b << endl;
cout << *b << endl;
cout << &b << endl;
cout << *(&b) << endl;
return 0;
}
result:
str
s
0x7ffdf39c27f0
str
I run my code on the web runoob online compiler
Why I get these results? I looked some questions about char*, but not enough for me to understand. Can someone explain that to me? Pictures are best.
I want to know more about it with books or blogs recommended.
By the way, usingchar b[] instead of const char*, I get the same results.
Thanks a lot for all of you.
I just want to know why a char pointer's value is not an address.
I think adress is like 0x7ffdf39c27f0. an memory adress.
But const char* b = "str". b is just str.
And I found that *b is the same as *("str").
So I want to know what happened in the memory? why a char pointer's value is not an address?
| To understand what the code outputs, you need to understand that C++ output streams (objects with a type such as std::ostream) and therefore objects (such as std::cout) have a number of overloads of operator<<(). The overload that is called depends on the type of argument provided.
I'll explain your second example, but the explanation for the first example is almost identical.
const char* b="st\0r";
cout << b << endl;
cout << *b << endl;
cout << &b << endl;
cout << *(&b) << endl;
cout << b expands to cout.operator<<(b) where b has type const char *. That overload of the operator function ASSUMES the argument points to (the first character of) a nul terminated string, which is represented in memory as an array of char that ends with a char with value '\0' (zero). The operator function outputs each character it finds until it reaches a '\0' character. The first '\0' found is the one YOU explicitly inserted after the 't', so the output st is produced. The fact that your string has a second '\0' after the 'r' is irrelevant, since the operator function stops at the first one it finds.
cout << *b expands to a call of a different overload of operator<<() that accepts a single char, and outputs that char. *b is the value of the first character in the string represented by b. So the output s is produced.
In cout << &b, &b has type const char ** or (equivalently) char const **. There is no overload of an output stream's operator<<() that accepts a const char **, but there is an overload that accepts a const void *. Since any pointer (other than pointer-to-member or pointers to functions) can be implicitly converted to void *, that conversion is performed (by the compiler), so the overload matches, and is called. That particular overload of the operator<<() prints the address in memory.
The implicit conversion in the third case doesn't happen in the first two cases, since a call that doesn't require an implicit conversion is a better match than a call which does.
In the last statement *(&b) is equivalent to b. This is the case because & is the address-of operator in this code, and the * is the dereference operator (which is the inverse of the address-of operator). So the last statement produces the same output as cout << b.
|
69,792,207 | 69,792,428 | Iterating through an array of objects C++ | I am trying to iterate through an array to objects to set different attributes of those objects. The attributes of my objects may change over time.
My code as a simplified example:
// MyClass.h
class MyClass
{
/* class definitions */
};
extern MyClass object;
// MyClass.cpp
#include MyClass.h
/* Constructors, Destructors, Functions */
// main.cpp
void reload_objects();
int main()
{
MyClass object[20];
reload_objects();
{
void reload_objects();
{
for (int i = 0; i < 20; i++){
object[i].setProperties(/*args*/);
}
}
I am getting an error error: No match for 'operator[]' (operand types are ‘MyClass’ and ‘int’). If I move the for loop into main it compiles and runs fine.
What is causing this error?
Would it be easier or in some way better to use std::vector<MyClass> object(20) in some way?
| There are several mistakes in your given code snippet. You can correct them as i have shown below. I have added comments wherever i have made changes.
MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
// MyClass.h
class MyClass
{
/* class definitions */
public:
MyClass() = default;
};
extern MyClass object[20]; //declare object as an array
#endif
MyClass.cpp
// MyClass.cpp
#include "MyClass.h"
/* Constructors, Destructors, Functions */
main.cpp
#include <iostream>
#include "MyClass.h"
MyClass object[20]; // define object here instead of inside main()
void reload_objects(); // reload_objects() doesnt take any argument by looking at its call and definiton
int main()
{
// MyClass object[20]; //don't define object here
reload_objects();
}
void reload_objects() //you had a semicolon here so i removed it
{
for (int i = 0; i < 20; i++){
object[i].setProperties(/*args*/);
;
}
}
Also don't forget to add the definition and declaration of your other member functions like setProperties in the above example for it to work. These are some of the changes that i made:
You should declare object as an array of size 20 inside MyClass.h.
Define object outside of main() inside main.cpp as i did in my example.
Declare the function reload_objects() with no arguments in main.cpp.
|
69,792,281 | 69,795,105 | static_assert evaluates non constant expression | Why does it working?
#include <cstdio>
template<auto x> struct constant {
constexpr operator auto() { return x; }
};
constant<true> true_;
static constexpr const bool true__ = true;
template<auto tag> struct registryv2 {
// not constexpr
static auto push() {
fprintf(stderr, "%s\n", __PRETTY_FUNCTION__);
//*
return true_; // compiles
/*/
return true__; // read of non-const variable 'x' is not allowed in a constant expression
//*/
}
// not constexpr either
static inline auto x = push();
};
static_assert(registryv2<0>::x);
https://godbolt.org/z/GYTdE3M9q
|
static_assert evaluates non constant expression
Nope, it most certainly does not. Constant evaluation has a strict set of conditions to is must obey in order to succeed.
For starters:
[dcl.dcl]
6 In a static_assert-declaration, the constant-expression shall be a contextually converted constant expression of type bool.
"contextually converted" is standard lingo for "we'll consider explicit conversion operators". The place where it may become counter-intuitive is when "converted constant expression" is defined.
[expr.const]
4 A converted constant expression of type T is an expression, implicitly converted to type T, where the converted expression is a constant expression and the implicit conversion sequence contains only
user-defined conversions,
[...]
The fine point is in the first sentence of the paragraph. The converted expression must be a constant expression. But the source expression doesn't have to be! So long as the conversion sequence is limited to the list in the paragraph and is valid constant evaluation itself, we are in the clear. In your example, the expression registryv2<0>::x has type constant<true>, it can be contextually converted to a bool via the user defined conversion operator. And well, the conversion operator satisfiers all the requirements of a constexpr function and constant evaluation.
The list of requirements for constant evaluation is rather long so I won't go over it to verify every bullet is upheld. But I will demonstrate that we can trip one of them.
template<auto x> struct constant {
bool const x_ = x;
constexpr explicit operator auto() const { return x_; }
};
This change immediately makes the godbolt code sample ill-formed. Why? Because we are doing an lvalue-to-rvalue conversion (standard lingo for access) on a bool when it is not permitted.
An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:
an lvalue-to-rvalue conversion unless it is applied to
a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or
a non-volatile glvalue that refers to a subobject of a string literal, or
a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable subobject of such an object, or
a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of e;
Going over the exceptions, none apply. So now registryv2<0>::x is not a contextually converted constant expression of type bool.
This also explain why true__1 is verboten. Same issue, access to an object that is disallowed.
1 - That's a reserved identifier. Two consecutive underscores belong to the implementation for any use. Not critical to the issue at hand, but take note.
|
69,792,467 | 69,808,694 | Memory check on macOS 12 Monterey? | Valgrind is not compatible with macOS 12 now, and I tried to add compile flag -fsanitize=address, but got link error:
Undefined symbols for architecture x86_64:
"___asan_init", referenced from:
_asan.module_ctor in main.cpp.o
"___asan_version_mismatch_check_apple_clang_1300", referenced from:
_asan.module_ctor in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Is there any way to make Valgrind compatible with macOS 12?
| Are there any patches via macports or brew that allow you to install Valgrind on macOS 12?
It's all a question of resources. I think that I'm the only active Valgrind dev that uses macOS, but my focus is on FreeBSD. It's a bit of a pity that Apple (market cap of $2.4 trillion at the time of writing) can't commit some relatively small amount of effort to achieve this. There are several IBM engineers contributing (directly for s390 and PPC and indirectly via RedHat).
The changes required to the Valgrind configure scripts are fairly minor.
Try this
clone https://github.com/LouisBrunner/valgrind-macos/tree/feature/macos_11pp2
edit configure.ac
add AC_DEFINE([DARWIN_12_00], 120000, [DARWIN_VERS value for macOS 12.0]) after line 430
add new versions for XCode 12:
after line 435
AC_DEFINE([XCODE_12_0], 110000, [XCODE_VERS value for Xcode 12.0])
and after line 555
12.*)
AC_DEFINE([XCODE_VERS], XCODE_12_0, [Xcode version])
;;
duplicate the case block for kernel version 21.0 (line 526), something like
# comes after the 20.0) case
21.*)
AC_MSG_RESULT([Darwin 21.x (${kernel}) / macOS 12 Monterey])
AC_DEFINE([DARWIN_VERS], DARWIN_12_00, [Darwin / Mac OS X version])
DEFAULT_SUPP="darwin20.supp ${DEFAULT_SUPP}"
DEFAULT_SUPP="darwin10-drd.supp ${DEFAULT_SUPP}"
;;
(ignore the suppression version for now)
run ./autogen.sh
run ./configure
run make
if that all works run ./vg-in-place yes
Doing the above plus a few more changes for DARWIN_12, I get
paulf> ./vg-in-place yes
==12358== Memcheck, a memory error detector
==12358== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==12358== Using Valgrind-3.18.0.GIT-lbmacos and LibVEX; rerun with -h for copyright info
==12358== Command: yes
==12358==
valgrind: m_mach/dyld_cache.c:244 (int try_to_init(void)): Assertion 'dyld_cache.header->mappingCount == 3' failed.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.