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 |
|---|---|---|---|---|
66,758,931 | 66,759,143 | CPP Guessing Game not working, its stops after i enter the name | I'm trying to make this kina guess game on C++, I'm a beginner and still learning.
What I'm trying to achieve is a guessing game of two const names, is very simple without errors but it's not working after I enter something. it should report until I find the correct name. Please also I don't want to change the structur... | You should change while(nameOkay = 0); to while(nameOkay == 0);.
Because = is an assignment, but == is operator of comparing (equality)
Read about it here
And here
|
66,759,134 | 66,762,838 | MFC: Why does this heap corruption happen? (array_s.cpp / afxcoll.inl) | Crashing Code
The following code makes my program crash (program exits) by heap corruption when the third line (the 'delete' command) is called:
1: CStringArray* pStringArray = new CStringArray();
2: ClassInDll::addToStringArray(_T("asdf"), *pStringArray);
3: delete pStringArray;
with
1: ClassInDll::addToStringArray(C... | It turned out that release and debug dlls were both being loaded (because of another dll):
msvcr100.dll
msvcr100d.dll
msvcp100.dll
msvcp100d.dll
The "modules" window sure does help, if you only know that you should look there.
Thanks to PaulMcKenzie and IInspectable for leading me into the right direction.
|
66,759,917 | 66,760,020 | Use memset for 2d array at specific row | recently, I have learnt about C++. Specially, I learned about memset function. But I don't know how to set value for 2d array at specific row
Example:
int dp[10][10];
// I want to set all values for dp[0] by using memset
// I can do it, by using For loop, like
for (int i = 0; i < 10; i++)
dp[0][i] = 1000;
I hav... | You can't do such a thing because memset write bytes.
For instance memset( dp[0],3,sizeof( dp[0] )) ; will write bytes == 3 in all 10 ints of dp[0].
So dp[i] == 0x03030303 for i in 0..9 !
|
66,760,712 | 66,760,918 | To store values in Array or vector of Objects reading from file c++98 | There are 6 columns entries in a file, where each column specifies values for(days, hours, Temperature, Relative Humidity, wind speed, global horizontal solar radiation) respectively. How we can store these values in array or vector of objects ? please help
1 1 13.7 58 2.7 0
1 2 13.5 64 1.4 0
1 3 13... | std::getline to extract each line, and std::stringstream to extract each value from this line:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
struct Data {
unsigned int days, hours;
float humidity, windSpeed, radiation;
};
int main()
{
std::vector<Data> data;... |
66,760,916 | 66,761,269 | CreateProcessA fails for some programs | Found the below snippet here on SO:
https://stackoverflow.com/a/35658917/9265719.
It executes a command without creating a window. CreateProcessA() returns TRUE for cmd.exe but for any program in C:\Program Files(x86)\Windows Kits\10\Debuggers\x64\ it returns FALSE and GetLastError() returns 2 (ERROR_PATH_NOT_FOUND).
W... | You are missing a space in the path, between "Program Files" and "(x86)". Should be:
char cmd[1000] = R"("C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe")";
|
66,761,259 | 66,761,440 | choose the best variable after comparing them | Surely the question was asked but I didn't know how to formulate my research to get relevant results.
In my problem, I have a point A and several other points B,C... on a plane.
I want to compare the distances between A-B, A-C, ... and return the closest point for example B.
Except that my way is not very optimized may... | You could put the numbers (/coordinates) into a container (say std::array) and use std::min_element to find the member from which the "from" point (A, in your example) has the smallest absolute distance. E.g.:
#include <algorithm> // std::min_element
#include <array>
#include <cmath> // std::abs
#include <iostream>... |
66,761,268 | 66,761,388 | Trying to print all permutations using only 4 and 7 upto n digits using recursion | I'm trying to print all permutations using only the digits 4 and 7 upto n digits using recursion like (4,7,44,47,74,77) for 2 digits.I'm trying to call the function recursively twice. I can't figure what's wrong with my code.
#include <bits/stdc++.h>
using namespace std;
vector<int> s;
void check(int a, int b)
{
... | You are using post-decrement which has no effect on the recursive call. On the other hand, it has an unintended effect on the second call. Just decrement the b before both calls and only once.
Coupled with non-defensive if(b==0), you get stack overflow when b slips into negative values and your program terminates.
Some... |
66,761,331 | 66,762,049 | Overloading operator== with `&&` and `const` qualifier cause ambiguity in C++20 | Consider the struct S with two operator== overloads of same && qualifier and different const qualifier:
struct S {
bool operator==(const S&) && {
return true;
}
bool operator==(const S&) const && {
return true;
}
};
If I compare the two S with operator==:
S{} == S{};
gcc and msvc accept this code, c... | The example would be unambiguous in C++17. C++20 brings change:
[over.match.oper]
For a unary operator @ with an operand of type cv1 T1, and for a binary operator @ with a left operand of type cv1 T1 and a right operand of type cv2 T2, four sets of candidate functions, designated member candidates, non-member candidat... |
66,761,481 | 66,761,585 | Function Encrypts But Won't Decrypt | So I am making a substitution cipher, where both Encipher and Decipher are handled by the same function after having specific parameters passed by separate respective functions. For some reason, it is working to encrypt, but it won't decrypt my message. In my code, a 'cipherAlphabet' is created from a keyword, and used... | The string cipherAlphabet contains only uppercase alphabets.
On the other hand, in the line
int oldCharIndex = oldAlphabet.find(tolower(input[i]));
it is searching for lowercase alphabets or non-alphabet characters.
Therefore, there will be no match.
Adding
if (oldCharIndex < 0) oldCharIndex = oldAlphabet.find... |
66,762,197 | 66,780,356 | How can we write optimized ARM code for C++ program using loop unrolling and code pre-loading? | Below are the given c++ and ARM code for same program. Can you tell me this ARM code is optimized or not and how many does the loop requires(The size of the array n is large, and is a multiple of 64 elements and exclusive-OR bit-wise operation with the 8-bit mask and produces an output array outArr.)? What should I do ... | I have no idea what 'code preload' means. There is data preloading with the pld instruction. It would make sense in the context of the sample code.
Here is the basic 'C' version given the assumptions,
The size of the array n is large, and is a multiple of 64 elements and exclusive-OR bit-wise operation with the 8-b... |
66,762,246 | 66,764,015 | Function-typed member variable selecting from iterators | Goals
A class with a function-typed member variable that can be used to choose a value from a range of values denoted by two iterators
Should work in C++14, but if a (much) better solution is only possible in 17 or 20, I'd be interested nonetheless
Problem and Solution Sketch
Below is a sketch of the envisioned solut... | std::min_element is a function template, there isn't much you can do with it by itself. Function templates are problematic - they can't be passed as a template argument, nor as function argument.
If you're OK with wrapping it in a generic lambda, then there's a generic solution possible:
template<class E, class F>
clas... |
66,762,327 | 66,762,754 | Two instances of keyword auto in cpp | First one being:
map <int,int> m;
//... some elements inserted
auto i= m.begin();
cout<<(*i).first<<(*i).second;
Here we are required to use the dereference operator *
Second:
map <int,int> m;
//... some elements inserted
for(auto i: m)
cout<<i.first<<i.second;
Why am I not required to use the * operator this time?
O... | auto i=m.begin() will give you iterator .. which is accessed more like a pointer (syntactically) when you want to access the value...
for(auto i:m) will copy current element of m (a pair) into i , i is a copy of element, not the element itself...
for (auto &i: m) will work on a reference, the original map is affected
|
66,762,362 | 66,762,600 | Optimization level affecting template overload resolution | I have run into interesting behavior regarding template overload resolution where it differed between release and debug build. I'd like to be able to understand the rules used by the compiler/linker that make it behave this way.
I've tried digging a bit and this is what I have come up with:
S.h
#pragma once
#include <... | The C++ Standard requires all template specializations to be declared before they are used.
See [temp.expl.spec]/6:
If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an impli... |
66,762,523 | 67,714,710 | Why does __nss_database_lookup take most of the time in my numerical C++ program | The line profiling output of google-pprof claims that most of the running time of my numerical C++ program is being spent in a function called __nss_database_lookup (see below). Apparently that function is for handling things like the passwd file on UNIX systems. My C++ program should only be doing numerical calculat... | A friend of mine met the similar issue today. Though it has been a while after you raised the question, but I still would like to answer it so that anyone else who reaches here can get some hints.
This is because some local symbols (which corresponds to static local functions in C/C++) are called, and these symbols don... |
66,763,102 | 66,763,134 | Why my C++ programme has stopped working? | I wrote C++ programme in vs code and When I run it, it ask me to enter the element value but when I enter the second time, it has stopped working. I don't know what the problem is but if you know the please help me to resolve the problem.
#include <iostream>
using namespace std;
class myArray {
public:
int total_s... | You used used_size and ptr without initializing them in a.setvalue(); and a.show();.
It seems
myArray(10, 2);
myArray a;
should be
myArray a(10, 2);
Also, as @Yksisarvinen points out,
ptr = new int(tsize);
should be
ptr = new int[tsize];
to allocate an array instead of single int.
|
66,763,279 | 66,763,856 | i am not able to figure it out how the .end function is working in this cpp program | It is a map problem In which I am taking a string and an int input form the user and then simply printing out values corresponding to the keys and if the key entered by the user has no corresponding value or the key doesn't exist then I am printing out Not found Now the thing I am not able to understand is how if (name... | The end() function return an iterator that represent the end of a container, here a map. If the function find(s1) return an iterator that is equal to the iterator given by end(), then it means that it didn’t find s1.
|
66,763,732 | 66,763,827 | CPP: Use of deleted function | I am trying to sort a vector that contains custom struct entries using a lambda function in c++ . But I get prompted the following error message
error: use of deleted function ‘dummy_struct& dummy_struct::operator=(const dummy_struct&)
The code looks like the following:
#include <regex>
struct dummy_struct
{
dum... | std::sort sorts vector by swapping it's elements in place.
This requires for your class to implement copy assignment operator (or move assignment), which compiler won't generate for you due to const fields in the class. For your example the only solution seems to remove the const qualifiers from the fields. If you don'... |
66,763,903 | 66,764,471 | What is the fastest way to find the positions of the first common entry in two vectors in c++? | I have two vectors u = {32, 25, 13, 42, 55, 33} and v = {18, 72, 53, 39, 13, 12, 28} for which I would like to determine the position of their first common entry, 13. For these example vectors, these positions are 3 and 5. What is the fastest way to find these positions? I have to do this operation many-many times.
| Assuming you don't have duplicate, you might use the following:
std::pair<std::size_t, std::size_t>
common_entry_indexes(const std::vector<int>& u, const std::vector<int>& v)
{
const std::size_t min_size = std::min(u.size(), v.size());
std::map<int, std::size_t> s; // might be `std::unordered_map`
for (std... |
66,763,926 | 66,765,541 | Which 'pointer'/'reference' type should I use in C++, and why? | I am a new C++ developer, and am taking a software engineering class at my university, and the project must be written in C++17, and able to be compiled with MSVC++ 19.
I have had several years of experience with Java and (less so with) C, but the transition to C++ has been... difficult, to say the least, and the compa... | C has two kind of type: objects and functions. All values are objects, some objects are pointers, the value of which is a location of an object or function. Everything is passed by value. Any pointer might be null.
Java has two kinds of type: primitives (that are only defined by the language) and reference to object (t... |
66,764,081 | 66,764,282 | Accessing Vector outside of class | Question 1
I am working on this BFS code retrieved from here and I changed the code a little bit and now I want to access the adjLists vector outside of the class in the main section.
// BFS algorithm in C++
#include <iostream>
#include <list>
using namespace std;
class Graph {
int numVertices;
std::vector<int>*... | Question 1
adjLists has type std::vector<int>*, so simple solution is simply returning that.
std::vector<int>* Graph::getVector() const
{
return adjLists;
}
Assigning what is returned ((a pointer to) an array of std::vector<int>) to std::vector<int> myVector requires some non-trivial conversion.
Question 2
std::ve... |
66,764,096 | 66,764,681 | Calculating std::hash using different compilers | I need to calculate the hash of a large string in windows and linux, and the result should be the same for both OS.
For a simple test code, I get different hashes for windows and linux using std::hash. This makes sense, since the actual implementation of std::hash for each compiler might use different algorithms.
Which... | In standard library hash algorithm is not fixed, may vary on different platforms/compilers.
But you can use very short and fast FNV1a algorithm for hashing, function with few lines of code, see below. You can read about it here.
It will give same result on all machines. But you have to fix set of params, 32-bit or 64-b... |
66,764,308 | 66,764,567 | define directive with parameter pack gives expecting an expression error | My C++ is very rusty from non use so this may be a very trivial issue. I am running a DLL project in C++ on Visual Studio 2019. I have a define directive with parameter pack such as the following:
#define FUNC(...) \
try \
{ \
(__VA_ARGS__); ... | Your macro call expands to ({ /* stuff */ });, which is not valid syntax. It may be that the code was originally compiled with GCC, which offers it as an extension.
You should remove the parentheses and semicolon from the macro expansion, leaving __VA_ARGS__ on its own to fill the enclosing scope.
|
66,764,403 | 66,765,643 | Cases of static and dynamic binding in C++ | The following code has 4 classes: Base1, Derived1 (derived from Base1), Base2, Derived2 (derived from Base2). Both base classes have integer data1 and display_data() functions. Both derived classes have integers data1 and data2, and display_data() functions.
I tried 4 cases in my code, which can be seen in the main fun... | Here is my attempt to explain it in a simple way :)
Static binding occurs when an object is associated with a member function based on the static type of the object (understand the type of its class).
Dynamic binding occurs when a pointer or reference is associated with a member function based on the dynamic type of th... |
66,765,121 | 66,772,844 | asio::strand<asio::io_context::executor_type> vs io_context::strand | Since latest versions of boost, asio comes up with its new executors and provides with asio::strand<Executor>. So it is now perfectly possible to use asio::strand<asio::io_context::executor_type> instead of io_context::strand. But they cannot be used interchangeably.
Could someone explain what is the difference in usa... | io_context::strand is "legacy". I assumed it exists for interface compatibility with code that still uses boost::asio::io_service (also deprecated).
As the comments reflect I've since found out that io_context::strand is not actually deprecated, although I see no reason why this is the case, and close reading of the i... |
66,765,599 | 66,888,013 | User defined-deduction guide for nested template-types | Q1 : Are user-defined deduction guides allowed at namespace scope ?
In the example here, GCC and Clang does not produce the same behavior :
https://godbolt.org/z/8W6hznEjo
#include <tuple>
template <typename T>
struct some_type;
template <template <typename...> typename T, typename ... Ts>
struct some_type<T<Ts...>>... | Quick-fix
The only work-around I found is to add a user-defined deduction guide only for Clang,
which is way sub-optimal in term of maintainability.
Live example on godbolt,
or see the sources below.
Why ?
GCC does not allow deduction guide in non-namespace context, Clang does.
Clang requires a deduction guide in this... |
66,765,785 | 66,766,080 | Little problem with pointer to object in a vector in c++ | Consider the following code:
class test {
public:
int n;
test(int n) : n(n) {}
};
int main() {
vector<test> v;
test one(1), two(2);
v.push_back(one);
v.push_back(two);
// obviously doesn't work since a copy of the object is stored in
//the vector ==> different memory addess
tes... | As it was said, you should use std::shared_ptr with std::weak_ptr. Below is a rewrite of your code with modern approach:
#include <iostream>
#include <memory>
#include <vector>
class test {
public:
int n;
test(int n) : n(n) {}
};
int main() {
std::vector<std::shared_ptr<test>> v;
std::shared_ptr o... |
66,765,906 | 66,766,274 | Vector Library: differences between .begin(), .rbegin(), cbegin(), crbegin() | I am not understanding the differences between
.begin() and .cbegin()
.rbegin() and .crbegin()
I usually use only .begin() and .end()
|
constexpr iterator begin() noexcept;
Returns an iterator that when dereferenced returns a reference to a non-const (mutable) element.
constexpr const_iterator cbegin() const noexcept;
Returns an iterator that when dereferenced returns a reference to a const (immutable) element.
constexpr const_iterator begin() const... |
66,766,146 | 66,766,224 | How can you return an array from a function in c++ | I want to make a simple function in C++ to get some practise. It should do the same thing as the range() function in python but for now a lot simpler. I ran into a problem that the array isn't returned properly from the function to the main function. I used to code below and got a weird error. Does someone know what th... | Try to pass the array as a reference instead of returning it.
#include "iostream"
void range(int max, int* ranger){
int n = 0;
while (n < max){
ranger[n] = n;
n += 1;
}
}
int main(){
int ranger[5];
range(5, ranger);
for(int k = 0; k < 5; k++){
std::cout << ranger[k] ... |
66,766,951 | 66,782,964 | multiple definition boost serialization | I use a library (https://github.com/tipaldi/flirtlib) that uses boost serialization on derived polymorphic classes. My problem is that I need to include the header in different places and this causes the linking error :
multiple definition of boost::archive::detail::extra_detail::init_guid
In the .h of the class the bo... | My crystal ball says that you missed the documentation that states you have to include the headers for all archive types that you are going to be using at the point of exporting macros.
From the docs: Exporting Class Serialization
BOOST_CLASS_EXPORT in the same source module that includes any of the archive class head... |
66,767,437 | 66,767,519 | Should you include files when invoking methods declared in it? | Apologies, I hate to ask something so simple, but I've failed to find an answer, probably because I don't know how to describe the question concisely.
Say you have a class X, and want to use it in z.cc.
I know you should include x.h in z.cc if you wish to have a field or param of type X so that the compiler knows how ... |
Should you include files when invoking methods declared in it?
Yes.
But what about if you wish to invoke a method X::doX()? Does this require an include, forward declaration, or neither?
Definition of the class is required to call member functions of the class.
Automatic type deduction can easily hide the types th... |
66,767,484 | 66,767,683 | My program returns 1 after Sleep() if I change a tcp socket to non blocking in a different thread | I have a thread that accepts client connections and makes the client sockets non blocking.
for(char Index = 0; Index < MAX_CLIENTS; ++Index)
{
if(ClientSockets[Index] == INVALID_SOCKET)
{
accept(ClientSockets[Index], (sockaddr *)&Address, &AddressSize);
unsigned long iMo... | You are using accept() incorrectly.
The 1st parameter of accept() is an input-only parameter, specifying which listening socket to accept a pending client connection for. That parameter is not an output parameter, like you are trying to treat it as.
You are passing ClientSockets[Index] to the 1st parameter accept(). ... |
66,767,828 | 66,768,514 | Ambiguous call operator overload weirdly resolved by introducing unrelated call operator - clang vs gcc | Consider the task of implementing an overload_two class so that the following code compiles:
int main()
{
overload_two o{
[](int) { return 1; },
[](char){ return 2; }
};
static_assert(o(0) + o('a') == 3);
}
A first attempt would look something like this:
template <typename F, typename G>
s... |
Yes. Name lookup for the name operator() is ambiguous because it found the name in both bases (see [class.member.lookup]/5.2). That's an error right there, don't pass GO, don't collect $200.
Yes. The unrelated operator() makes name lookup succeed by hiding the base class members. Because your lambdas are captureless, ... |
66,767,858 | 66,768,165 | Variadic template expansion with aliases? | So in a codebase I inherited we have a messy utility file along the lines of:
template <typename T, std::enable_if_t<(sizeof(T) == 1)>> int doA(const T *Data, size_t Size);
template <typename T, std::enable_if_t<(sizeof(T) == 1)>> int doB(const T *Data, size_t Size);
template <typename T> int doA(T &Input)
{ return d... | I suppose that, instead of your couple of using declarations, you can write a couple of C-style macros.
But I consider C-style macros as distilled evil, so I propose two simple conversion functions
template <typename ... Args>
auto doA (Args && ... as)
{ return do_t<true>(std::forward<Args>(as)...); }
template <typen... |
66,767,995 | 66,768,397 | Get QLabel's rectangle width | I have the following code:
QLabel *la = new QLabel(ui->lineEdit->text());
la->setStyleSheet("background-color : #4682b4; color: white; font-size: 25px; padding: 8%;");
int w = la->fontMetrics().boundingRect(la->text()).width();
Problem is I can't the proper width of the QLabel. w is not considering the changes made wi... | Size updated on paintEvent, you can get size with zero timer.
la->setStyleSheet("background-color : #4682b4; color: white; font-size: 25px; padding: 8%;");
QTimer::singleShot(0,[=](){
int w = la->fontMetrics().boundingRect(la->text()).width();
});
or you can call qApp->processEvents(); to spin event loop manualy.
... |
66,768,015 | 66,768,138 | Are range adaptors lazy in regard to arguments behind the viewable range? | The C++20 standard says in [range.adaptors.general] that range adaptors
evaluate lazily as the resulting view is iterated.
On the other hand, there is a remark in [range.filter.view] for filter_view's begin function mentioning caching the result. To what degree are the adaptors lazy then?
When executing following cod... | Remember that, in the C++ iterator model, positioning and access are two distinct operations. However, a filtering iterator is one whose position is based on accessing the range it is filtering. That is the nature of the iterator.
To find the beginning of a filtered range requires finding the first position in the unde... |
66,768,109 | 66,768,177 | Difference between destructors in my class | I'm implementing a simplified unique pointer. Everything was pretty clear, but I wonder about the destructor in my class.
Should it be ~unique_pointer(){obj->~T();} or ~unique_pointer(){delete obj}?
I really don't see a difference between these. Can you explain how they work?
Below is the whole class:
template<class T>... |
It should be ~unique_pointer(){obj->~T();} or ~unique_pointer(){delete obj}. I really don't see difference between each other.
obj->~T() destroys the pointed object. If the object is stored in dynamic memory, then the memory is not dealloated. If nothing else deallocates the memory, then the memory is leaked. Given t... |
66,768,365 | 66,768,430 | Class' has not been declared error when I declared it | I'm making a little shell that can just do random stuff. Bt whenever i compile i receive the error 'Shell' has not been declared
I declared the class shell and the object i n main.cpp, i've looked for a while and nothing. I'm new to oop so this may be pretty stupid but i've done wha to know
I'm using 3 files
main.cpp:
... | You should
Write definitions of class functions in .cpp files.
Write declarations of class functions in .h files.
Include .h files.
You actually did
Write definitions of class functions in .h files.
Write declarations of class functions in .cpp files.
Include .cpp files.
Try this:
main.cpp:
#include <iostream>
#inc... |
66,768,486 | 66,768,658 | GDI Object leak on System.Drawing.Bitmap.GetHicon() | I've seen similar questions but none satisfies my scenario.
I am fixing a GDI Objects leak on a C++ Windows Form Application.
This is the Exception it throws:
A generic error occurred in GDI+. at System.Drawing.Bitmap.GetHicon()
This is the GetHicon call at the line where the crash happens:
this->notifyIcon1->Icon=Ic... | Try this:
IntPtr iconHandle = ((Bitmap^)imgsApp->Images[0])->GetHicon();
Icon ^newIcon = Icon::FromHandle(iconHandle);
this->notifyIcon1->Icon = (Icon^) newIcon->Clone();
newIcon->Dispose();
DestroyIcon((HICON)iconHandle.ToPointer());
Per Icon.FromHandle: should I Dispose it, or call DestroyIcon?:
Conclusion: After I... |
66,768,578 | 66,769,326 | C++ XOR linked list, deleting data | I have to do XOR linked list. Now im at point that i want to proper way clear memory. I did something like this but it seems doesnt work.
Minimal code i could add to work
void deleteAll(Data* head)
{
if (head == NULL)
cout << "Empty list." << endl;
else
{
if (XOR(head, NULL) == NULL)
... | In deleteAll you have a line preventing all deletions:
if(XOR(head, NULL) == NULL) { // remove this line
Your deleteAll functions also takes a Data* and all changes you make to head will be local to the function only. A minimal change needed that should make it work is to take head as a Data*& - that is, a reference... |
66,768,670 | 66,801,859 | How to correctly share an object between .exe and .dll? | I have to access an object in .exe which is created and stored in .dll's address space. There's a lot of answers that mention IPC as a solution but I'm not sure how it can help. IMO, IPC is just a message "chat" between processes and can share primitives by recreating them on caller side (.exe). I can't recreate the ob... | IPC is a broad umbrella term that covers all inter process communication, not just shared memory (which is nothing like a "chat", by the way).
Luckily you don't need any kind of IPC, since you don't have different processes. The dll and the exe share the same address space, so simply return the pointer to the construct... |
66,768,990 | 66,770,184 | How to simply get audio amplitude in Qt | I am trying to make a progress bar which will vary it's value dependent on the real time amplitude of my microphone (default input device). I believe the missing key here is to use QIODevice::readAll() but I do not understand how QIODevice works with QAudioInput.
QAudioInput *audio;
QAudioFormat formatAudio;
formatAudi... | The solution is to create a QIODevice that is passed to the start() method (the solution is inspired by the official example Audio Example).
#include <QtWidgets>
#include <QtMultimedia>
class Device: public QIODevice{
Q_OBJECT
public:
Device(QObject *parent=nullptr): QIODevice(parent)
{
}
Q_SIGNALS:
... |
66,769,195 | 66,769,413 | Partial build of Qt6 from source | I need to install Qt6 on Ubuntu 18. Since qt6 is not in the repositories (or is it?), I have to compile them from the source code. However, I do this on my VDS server, which is not very powerful (2 cores, 4GB of RAM), so I do not have enough power for standard Qt6 compilation (compilation crashes with errors like "I do... | The old Qt5 way is to pass -skip to the configure command line. e.g. configure .... -skip qtremoteobjects -skip qtwebengine According to the Qt6 build documentation, this option still exists. (Scroll near the bottom of that page on "Excluding Qt Modules"). In your case, you will probably be passing a lot of -skip sta... |
66,769,263 | 66,772,781 | Strandify inter coorporating objects for multithread support | My current application owns multiple «activatable» objects*. My intent is to "run" all those object in the same io_context and to add the necessary protection in order to toggle from single to multiple threads (to make it scalable)
If these objects were completely independent from each others, the number of threads run... | You're mixing vague words a bit. "Activatable", "Strandify", "inter coorporating". They're all close to meaningful concepts, yet, narrowly avoid binding to any precise meaning.
Deconstructing
Let's simplify using more precise concepts.
Let's say we have objects of type A and type B, all of them served by the same io_c... |
66,769,506 | 66,769,549 | When we need to remove constness of a variable , usage example? | Hello I'm new to c++ I've read that if I've a const variable I can remove its constness and update the variable as I please but in general it defeata the purpose of const . Can someone explain why one would ever make something const to remove its constness later?
| Mostly you should not do it, but some time you are stuck with a third party library which expects a char* ,but in your implementation you have the field marked as const , then you need to temporarily cast away the constness then make the function call.
|
66,769,590 | 66,772,297 | How do I allow NoneType Arguments OR a callback function to be passed to a function in ctypes | I've started writing a very simple Python binding around a C/C++ library, which I can't share here for legal reasons as I don't have permission.
This contains a WINFUNCTYPE() as a callback, which can then be used to decorate a function to use as the callback in python, and is defined in the argtypes of my function that... | You can give it a null function pointer by passing address 0 when creating the callback:
func('string', callback(0), 0, 1, 2)
In fact I looked at the link in the OP's posted answer and later in the thread it has basically the same thing...cast None to the callback type, e.g. cast(None, callback).
|
66,769,683 | 66,769,761 | Trying to create a basic calculator | However when Input "12 + 3" it outputs "154" or if I input "12+1" it outputs "1312". Multiplication also doesn't seem to work consistently. Division seems ok for the most part
#include <iostream>
int main()
{
int firstNum, secondNum, res;
std::string op;
std::cout << "Enter de... | The 4 in 154 and 12 in 1312 are the result of division.
You have two errors:
You have extra spaces in " - ", " * ", and " / ", preventing them from matching to op.
You have an extra semicolon after else if(op==" / "), having it do the division unconditionally.
Try this:
#include <iostream>
int main()
{
int firs... |
66,769,830 | 66,769,973 | Type of ternary operator integer expression when used in aggregate struct initialisation | I've run into an interesting warning (with GCC and clang -Wnarrowing at least, haven't tested other compilers), when aggregate initialising a struct using a ternary operator expression (see below code). I don't understand why the type of the expression is apparently considered int in the aggregate initialisation case, ... | The type of b ? 1 : 0 is certainly int.
Brace-initialization (including aggregate initialization) is not allowed to perform narrowing conversions, such as a conversion from a signed type to an unsigned type. This is a narrowing conversion because some values in the source type (i.e., negative numbers) cannot be represe... |
66,770,002 | 66,770,058 | Accessing the pointers of a static function | I am new to C and C++. I have defined a static function which has a pointer 'ptr'. How can I access the pointer outside the function?
#include <iostream>
using namespace std;
static void accessArr(uint8_t arr[]);
int main()
{
uint8_t arr[] = {1,2,3,4,5};
accessArr(arr);
cout << *ptr <<endl;
ret... | The name ptr is not declared and visible in main. Just declare the function as returning a pointer like for example
static uint8_t * accessArr(uint8_t arr[])
{
return arr;
}
And in main you can write
cout << *accessArr( arr ) <<endl;
Or
uint8_t *ptr = accessArr( arr );
cout << *ptr <<endl;
|
66,770,022 | 66,770,721 | Advice on c++ class interface design: how would you name these two methods to make them obvious? | I have a very simple concrete class that represents a point in 2D space, it has two methods to shift the point given a radius and an angle: one modifies the object itself, the other creates another object leaving the first one unchanged:
template<class T =double> class cls_2DPoint
{
...
cls_2DPoint<T>& polar_mo... | My suggestions.
Use namespace instead of prefix for class name
namespace cls2D
{
class Point { ... };
}
Add class Vector
namespace cls2D
{
class Point { ... };
class Vector { ... };
}
Define operator methods
Define operator methods that work with the two object types. Prefer non-member functions if you can g... |
66,770,198 | 66,770,553 | Difference between capturing return value by `const auto&` and `auto` | I've seen code like const auto& now = time(nullptr);
I think the purpose of assigning the rvalue returned by time is to extend the return value's lifetime, as explained in the GotW post. But why not use const auto now = time(nullptr)?
Why do we want to extend the lifetime of the return value here? and is there any perf... | In the shown example, there is no reason to use a reference. The behavior of the snippet is identical with or without it.
In general, it's a good idea to use a reference to avoid incurring needless copies, so there's no harm in getting into the habit of using references, even if it doesn't make a difference in some cas... |
66,770,267 | 66,770,282 | Can a member operator be used without referring to the "this" pointer? | I would like to overload the [] operator and use it within a member function without referring to the this pointer, because the point of overloading, at least in this case, is brevity. I don't think it can be done, can it? It seems inconsistent that I can access member functions without dereferencing this, but not memb... | You can use it without this like
operator[](k);
|
66,770,371 | 66,771,156 | Getting issue with placement new and delete operator | I have written the following code for placement new and delete operator functions. Can you please tell the issue with the code below.
// new_operator.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
class Mem
{
public:
void* alloc(si... |
Placement delete is called to free memory when a constructor called from placement new fails. You are not supposed to call any destructors from any version of operator delete, because operator delete frees memory that is left after an object that used to reside there is destroyed (or was never constructed to begin wit... |
66,770,747 | 66,770,836 | Is it OK to save a reference to the object managed by a shared_ptr? | Here's a working version of what I'm doing.
#include <memory>
using namespace std;
struct thing {
int blah;
};
struct parentObj {
parentObj(thing & incomingThing) : isThisOK(incomingThing) {};
thing & isThisOK;
};
int main()
{
shared_ptr<thing> thingInstance = make_shared<thing>();
shared_ptr<pa... | It is just as okay as this:
#include <memory>
using namespace std;
struct thing {
int blah;
};
struct parentObj {
parentObj(thing& incomingThing) : isThisOK(incomingThing) {};
thing& isThisOK;
};
int main()
{
thing thingInstance;
shared_ptr<parentObj> theObj = make_shared<parentObj>(thingInstanc... |
66,770,783 | 66,770,864 | 'no matching function call' when inserting type into std::map | I have the following setup:
an Instruction struct:
struct Instruction {
Instruction( const std::string& _opcode) : opcode(_opcode) {}
std::bitset<6> opcode;
};
a struct containing a map which maps a string to an instruction:
class Parser{
Parser();
private:
std::map<std::string, Instruction> instr_map;... | instr_map["add"] creates a new element if the specified key does not exist yet, and then returns a reference to that key's value. You are then assigning a new object to that referenced value. So the key's value has to be default-constructible first, but your Instruction is not, hence the error.
If you want to skip th... |
66,770,807 | 66,771,098 | Expression SFINAE and hard errors in c++ | I'm confused about why one of these functions gives a hard error, and the other does not:
#include <utility>
template <typename ...Args>
auto ffExists1()
-> decltype(ff(std::declval<Args>()...)); // Attempts to see
// whether you can call ff (which is not defined or declared)
// with arguments of type Args... ... | In ffExists2, ff doesn't depend on template parameters, thus the lookup for it (i.e. finding the function by the provided name) is done at phase one of two-phase lookup, i.e. when the compiler first sees the template, as opposed to when the template arguments are substituted into it.
Because of this, even if ff was def... |
66,770,920 | 66,770,949 | Why don't overloaded "<<" and "++" work together? | Firstly, i'm pretty new to C++ and OOP, so sorry if asking silly questions. So, here it is, I overloaded the "<<" and "++" (postfix and prefix) and they work fine alone. But they seem to not work when combined. I don't get why, both ++-s return a foo type object, so I thinked that "<<" should work fine...
#include <ios... | Your stream output overload should take your foo references as const. After all, they shouldn't be modifying the foo's passed in:
friend istream& operator<<(istream& in, const foo& S);
A non-const reference parameter (like your foo& S), must have an l-value passed to it. Since your increment operator returns an r-valu... |
66,771,420 | 66,771,618 | Getting data from a file with different lengths of data c++ | I'm trying to get grades from a txt file
NAME ID AM_CLASSES AM_GRADES GRADES AM_GRADES GRADES AM_GRADES GRADES AM_GRADES GRADES
---------------------------------------------------------------------------------------------------------------------------------------------------------------... | The data may be variable length, but it has a pattern to it. You can make use of operator>>, as each class list is preceded by the number of classes, and each grades list is preceded by the number of grades.
Try something like this:
#include <fstream>
#include <string>
#include <vector>
#include <limits>
using namespa... |
66,771,436 | 66,771,491 | 'using' keyword with multiple overloads | I have been reading how to use using-declaration and was wondering what happened when I have multiple overloads. In the examples given, it looks as if this is all or nothing or is it possible to pull only a certain signature in scope?
Suppose I have the following classes:
class A
{
public:
void function(int value);
... | It's all or nothing, you can't pick only specific overloads.
I would have to move the declaration of such a function to protected or private to disable access to it, right?
It wouldn't work. If you move even some of them to private, then using A::function; will apparently cause an error.
And if you make them protecte... |
66,772,352 | 66,772,649 | Java Iterator in C++ | I am a Java user and I am getting into C++ and in Java it allows classes to reveal Iterable types so clients can traverse some instance's collection of data. Is there any way to obtain this functionality in C++? This is an example of what I am trying to implement in c++.
public Iterable<String> keys() {
Queue<Stri... | C++ is not object oriented in the same way as Java. While containers do have some uniformity in their interface, they do not implement a common interface type or derive from a common base. These types of implicit interfaces allow compile-time polymorphism only, so you there isn't any Iterable abstraction equivalent whi... |
66,772,666 | 66,772,671 | What's the difference - struct std::hash<T> vs namespace std { struct hash<T> }? | Is there any difference between these two variants of std::hash specialization?
template <>
struct std::hash<T> {
size_t operator()(const T& x) const {
return ...;
}
};
namespace std {
template <>
struct hash<T> {
size_t operator()(const T& x) const {
return ...;
}
};
} // end of std
| This one:
template <>
struct std::hash<T> {
size_t operator()(const T& x) const {
return ...;
}
};
Is non standard. It's an extension provided by your compiler and is non portable.
This one:
namespace std {
template <>
struct hash<T> {
size_t operator()(const T& x) const {
return ...;
}
};
} // end of ... |
66,772,875 | 66,772,966 | C++ Proper way to set pointer to NULL value | i have quick question (i think quick). I have to check if pointer is NULL after delete data pointed by pointer. In my case i have data stored in fl->first and i want to clear this data. After clear by delete fl->first i have to check if fl->first pointer is NULL. I read a lot of posts that
delete fl->first;
fl->first =... | You should not use the NULL macro in C++. Using nullptr literal is preferable instead. This is because the macro is ambiguous in some cases which may lead to confusion.
Besides that, you should typically avoid owning bare pointers, and thus deleting anything directly is usually not a good idea.
|
66,772,923 | 66,772,989 | Randomly occurring Seg Fault in Randomized Binary Search Tree | I am writing a function to take a Node* T and int k as parameters, where T is a pointer to the Root node of a Binary Search Tree, and k is the element to insert. The function should, with 1/T->size probability determine if k should be inserted as the new head. If the probability fails, it recursively calls itself using... | Node n(T->key); // n is a local object that exists until we return
Node* oldHead=&n; // oldhead is a pointer to n
oldHead->size=T->size;
oldHead->left=T->left;
oldHead->right=T->right;
T->key=k;
T->size++;
T->right=nullptr;
T->left=nullptr;
... |
66,773,247 | 66,773,373 | libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: mutex lock failed: Invalid argument | I had some code for a thread pool that has been working on my Ubuntu machine for quite some time. The project is a CMake project, and I believe it was using a recent version of g++ as the compiler.
I just tried to run the code on a Mac, CMake tries to use AppleClang 12.0.0.12000032, and I'm hit with
libc++abi.dylib: te... | Here is where that exception is being thrown from: https://github.com/llvm/llvm-project/blob/main/libcxx/src/mutex.cpp#L35
This typically happens when .lock() is called on a mutex that is not yet constructed, or has already been destructed. This can happen for mutexes with static storage duration when they are accesse... |
66,773,298 | 66,810,684 | Error passing a lambda as default argument | The code below compiles fine, until I uncomment the line: lambda();. Why does it compile if I don't use the function relying on the default argument, but when I try to use the default argument, it doesn't compile anymore?
#include <iostream>
int main()
{
static auto lambdaDefaultParameter = []() // must be stat... | Apparently auto is having some trouble. Specifying the type explicitly works on MSVC. g++ still doesn't compile it, because if thinks a static lambda is a local variable. MSVC only thinks it's a local variable when I don't use the static keyword in lambdaDefaultParameter.
#include <iostream>
int main()
{
static au... |
66,773,744 | 66,773,768 | C++ The if statement is still true even when only one condition is met | I am creating a tic tac toe program in c++ and am almost finished with it, the issue I'm having is when the game needs to end in a tie. I created an if-statement to check when specific combinations are selected and it finds it true even when only one condition is met.
Here is the code...
//takes the users selections... | The condition:
b1== "O" || "X"
evaluates as:
(b1=="O") || "X"
which is always true. You probably want:
(b1=="O" || b1=="X")
|
66,773,759 | 66,861,171 | Is it possible for this to be an infinite loop? | I am looking for advice on the following function:
void f( std::vector<short> v ){
for(unsigned int i=0; i < v.size(); ++i){
// anything
}
}
My code looks like this, but someone told me it's possible for this to loop forever. I don't understand what conditions might cause that, because it looks normal to... | Yes, this might very well be an infinite loop.
void f( std::vector<short> v )
{
for(unsigned int i=0; i < v.size(); ++i)
{
// anything
}
}
v.size() is a size_t, which on some platform, like mine is 64-bit unsigned. So, a value like 2^63 is possible.
unsigned int, might be smaller than size_t. So, it... |
66,773,946 | 66,779,027 | Does as-if rule allow this kind of execution reordering | As we know, the compiler or the CPU may reorder the execution as they want, only if they follow the as-if rule. For example, if we have such a piece of code:
C = A + B;
D = E + F;
The compiler or the CPU may execute D = E + F before C = A + B. I can understand that.
Now let's talk about another case.
Saying that I hav... | Reordering and multithreading are 2 different things:
Via multi threading, possible outputs are:
"a - 1", "a - 2", "b - 1", "b - 2"
"a - 1", "b - 1", "a - 2", "b - 2"
"a - 1", "b - 1", "b - 2", "a - 2"
"b - 1", "b - 2", "a - 1", "a - 2"
"b - 1", "a - 1", "b - 2", "a - 2"
"b - 1", "a - 1", "a - 2", "b - 2"
You just ha... |
66,774,650 | 66,774,720 | no instance of overloaded function matches the specified type (C++) | #include <iostream>
#include <string>
using namespace std;
class student {
private:
string sname;
float gpa;
public:
student(string name, float g = 0.0);
~student();
};
struct student {
string name;
int gpa;
void display();
};
student::student(string name, float g) { // **this is where I... | compiler think student as structure,
change student sturture name
|
66,775,367 | 66,775,404 | Fill array with random numbers within a specified range (C++) | I am writing code that fills in an array the size of 10 integers with random numbers within the range of 0 to 9. The code I have works but it fills all 10 slots with the exact same random integer, is there a way to randomize the integer per array item?
This is the code I have:
#include <iostream>
#include <ctime>
#incl... | You are using exact same integer in each initialization. for loop should be like that
for(int i = 0; i < size; i++){
arr[i] = (rand() % 10);
}
|
66,775,523 | 66,775,805 | cpp arrays terminate called after throwing an instance of std::bad_alloc | I am sorry if this is really basic question I am just starting out with programming I have looked up online couldn't find anything to solve this issue.
while running my program I encountered this message "what(): std::bad_alloc" this is the first time ever for me, the program will run 2 out 5 times and for the rest I ... | Your program is throwing an std::bad_alloc exception at some point and, since your are not handling this exception, it halts. This is due to some flaw on memory management.
Check your bubble-sort algorithm. Specifically, the for loop:
for (int i = 0; i<NUM_NAMES; i++)
{
if(names[i]>names[i+1]) // Do you notice the ... |
66,776,910 | 66,777,874 | SPIFFS save return key into string | When reading a .txt file line by line with SPIFFS on my ESP32 it saves the return keys also, is there a way to prevent this?
Function for reading:
String line_one, line_two;
void readfiles() {
char buffer[64];
int i = 0;
File file0 = SPIFFS.open("/0.txt", "r");
while (file0.available()) {
int l = file0.rea... | I found out the answer by myself.
It has something to do with "carriage return" (/r) and "line feed" (/n).
Windows Notepad do a CR and then a LF at the end of a line, so i solved this error by removing the LF with notepad++ and changing a line in my code.
From this:
int l = file0.readBytesUntil('\n', buffer, sizeof(buf... |
66,777,284 | 66,777,851 | Can I change a child class's variable and return it using the parent class's function | So I have a parent class Transport and a child class Horse.
The parent class has a virtual function go() which the child uses to let the child object know how far to travel.
The parent class also has a method called get_dist_travelled() which returns the total distance travelled, but when called for the child object I ... | Your horse has two sets of members. Those inherited from Transport named kms and kmsAll and those defined in its class definition called kms and kmsAll.
The members of Horse are shadowing those inherited from Transport. Hence in methods of Transport you are working on members of Transport and in methods of Horse you ar... |
66,778,378 | 66,778,515 | How to move a unique_ptr from one set to another? (C++) | The code below is giving the error: Call to deleted constructor of 'std::unique_ptr<int>' 'unique_ptr' has been explicitly marked deleted here passing argument to parameter 'item' here.
Could someone please explain why this is? I would have thought everything would be fine because I'm using std::move in the call to foo... | Use c++ 17 extract() function.
example
#include <set>
#include <memory>
#include <iostream>
int main() {
auto s = std::set<std::unique_ptr<int>>{};
s.insert(std::make_unique<int>(10));
std::cout << s.size() << "\n";
auto it = s.extract(s.begin());
// Pointer type here just for clarification
... |
66,778,684 | 66,779,010 | How to overload a function taking variable number of arguments | I need to distinguish (overload) between two functions - one takes a single const char* argument and the other takes at least two arguments - a const char* followed by one or more arguments.
i.e. basically:
void f(const char *str);
void f(const char *format, ...)
I want the first version to be called for f("hello") an... | If you use a vararg template you can accomplish what you want:
#include <iostream>
void f(const char* str)
{
std::cout << "single arg: " << str << "\n";
}
template <typename ...T>
void f(const char *format, T... args)
{
printf(format, args...);
}
int main()
{
f("hello");
f("formatted %d", 10);
}
|
66,778,801 | 66,778,957 | difference between vector<thread> and vector<thread *> | Question about threads in C++
What are the advantages and disadvantages of using one or the other ?
vector<thread> tvec;
...
or
vector<thread*> tvec; // or vector<shared_ptr<thread>> tvec;
...
| std::thread is a tiny class containing mostly just the thread ID or handle. It is also movable, and so is a good candidate to be stored in a vector by-value.
So it's easiest and most readable to store them by-value, as it vector<thread> tvec;.
In addition, the form vector<T*> carries non-owning semantics, and so is pro... |
66,779,382 | 66,801,229 | Why is my D code for finding prime numbers much faster than my C++ code? | I coded two small projects in C++ and D(lang) respectively to calculate a given number of prime numbers. The code is very similar in both projects. However, my D code runs MUCH faster than my C++ code, even though C++ is said to be faster. I use dmd and dub for compiling D code and clang (LLVM 11.0) with Visual C++ for... | If you slightly change your main.cpp
diff main.old.cpp main.cpp
9c9,10
< for(unsigned i = 2; i < isqrt(number)+1; i++)
---
> int max = isqrt(number) + 1;
> for(unsigned i = 2; i < max; i++)
And rebuild your C++ code again
g++ -O3 -o cppisqrt isqrt.cpp main.cpp
You will see that C++ version is only slightl... |
66,779,727 | 66,779,989 | How to make a function argument do something before and after being passed in one-liner in C++ | I would like to make an object do something before and after being passed as an argument into a function, but (1) without modifying the function and (2) in a neat way.
Here is the first one that comes to my mind, with RAII.
However, I think the expression (x.lock(), x) is ugly.
I think there would definitely be a good ... | You cannot do it when the function and call are:
void f(const A& obj);
f(x);
and you are not allowed to change these. There is no way to make the object aware of a reference being taken.
You can however, call a different function:
void f2(const A& obj) {
obj.before();
f(obj);
obj.after();
}
f2(x); // <... |
66,779,930 | 66,780,125 | C++ Final class with polymorphism | I have an abstract class which defines the basic functionality of a submodule for my application.
Let's call this abstract class IProdBridge.
IProdBridge contains virtual and non-virtual methods and also some pure-virtual methods.
Because this software runs on a multitude of different platforms, the base class handles ... | I've found the error
This is probably one of the worst cases of PEBKAC, but maybe this will save someone else from searching as long as I have.
I'm not entirely sure why this didn't cause a plethora of other compiler errors, but the issue was with my namespace.
This class is nested within two namespaces:
namespace MyAp... |
66,780,643 | 66,781,574 | Declaring array size for dynamically allocated array with initializer list | I'm trying to initialize a dynamically declared array with an initializer list but I noticed that I have to provide the array size with GCC or I get an error. Trying the same using MSVC does not cause any errors if the array size is left out. Is providing array size when using an initializer list with dynamic arrays ma... | This is P1009R2: Array size deduction in new-expressions, which was implemented for C++20.
Bjarne Stroustrup pointed out the following inconsistency in the C++ language:
double a[]{1,2,3}; // this declaration is OK, ...
double* p = new double[]{1,2,3}; // ...but this one is ill-formed!
Jens Maurer provided the explan... |
66,780,753 | 66,789,161 | Compiler optimizing return by reference vs. by value | I wanted to understand the specific optimization if any which can be performed by the compiler here .
The two get functions get() return a string by reference and another by value. Map is global in nature.
I want to understand this as it common thing is done, so what will happen in case we have a map of objects or map ... | From the C++ language perspective there is no guarantee that the copy in get2 will be elided. Mandatory return value optimization covers only prvalue operands (i.e. values created in the function call itself). Even the "permitted" optimization doesn't cover pre-existing objects.
So we can only hope that compilers today... |
66,781,128 | 66,782,399 | Qt dialog not showing its widgets | I would like to create custom QT dialog (non-modal). Problem with my implementation is that it shows only dialog window with title, and no widgets that I've added to it.
Code below (I've ommited most of it, added just dialog and main window parts).
MainWindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
publ... | In DialogAddUpdateItem.cpp the centralWidget has no parent, therefore it is not bound to anything and therefore not displayed. You should modify this:
centralWidget = new QGroupBox;
into this:
centralWidget = new QGroupBox(this);
Now the DialogAddUpdateItem will be the parent of the centralWidget and it should displa... |
66,781,240 | 66,781,659 | Is it possible to create a view of references from objects? | To illustrate what I mean: I have three objects:
Foo first, even, odd;
And I want to construct a view consisting of references to these objects like this: first&, odd&, even&, odd& ... up to N. To be able to iterate over them:
for (const auto & obj: my_view) {
// obj is equal to first&, odd&, even&, odd&... and so... | Firstly, I recommend starting off with arrays of Foo objects instead of distinct variables. This isn't necessary as you can use spans instead, but this is a bit more straightforward:
Foo first[1] {};
Foo even_odd[2] {};
Ranges-v3 has cycle and concat views that are useful in this case. They aren't in the standard libr... |
66,781,323 | 66,782,280 | OpenSceneGraph: analysing a scenegraph | I want to read a 3D Model through OSG and learn the 3D model information about vertices, normals and texture coordinates etc.
I do not understand the code below (complete tutorial from here ). why are we using prset->index(ic) as an index? I am confused. (* verts) is the vertex array but what is the prset->index(ic) ?
... | If your drawable uses indexed primitives, you need to de-reference the triangle vertices looking into the indices array, as you might re-use shared vertices of the vertex array.
Something like this.
|
66,781,419 | 66,788,066 | Reading txt file into linked list queue | I got a problem, when im reading data from txt file into linked list queue program(main.cpp, queue.cpp, queue.h). So I tried two methods, but it doesn't work properly.
In txt file I got some lines, for example four. Firstable, we read data from file, then call display() function in switch loop.
First number in line is ... | I got this:
while (!input.eof()) {
if (input >> temp->key >> temp->type >> temp->quantity >> temp->price) {
if (temp->key == 1) {
item1.enqueue(temp->key, temp->type, temp->quantity, temp->price);
}
else if (temp->key ==... |
66,781,589 | 66,781,655 | Unable to assign values to stack | Here is the code for my Stack Implementation
class stack
{
private:
int top;
int arr[10];
public:
Stack()
{
top = -1;
for(int i=0; i < 10; i++)
{
arr[i] = 0;
}
return 0;
}
//further code ... | Fixing the typing errors and removing the return "solves" the problem. But your output is not reproducible at all:
#include <iostream>
class Stack
{
private:
int top;
int arr[10];
public:
Stack()
{
top = -1;
for(int i=0; i < 10; i++)
{
... |
66,781,652 | 66,783,021 | How to use + operator of a base class then return derived class? | I have two classes. The base class, called String stores a const char* and the lenght of it, len. The derived class, called UString should has to manage an upperCase static boolean variable. If this is true the string in ostream has to be full uppercase. (this is a university task)
Where I have the problem (test file):... | Your
UString& UString::operator=(String const &s)
implementation first adds two strings, and then throws away the result, as the result is a temporary value:
String::operator+(rhs_s);
When you change it into
UString UString::operator+(const UString& rhs_s) {
return UString(String::operator+(rhs_s));
}
it wil... |
66,781,742 | 66,781,898 | Swapping vector rows | I want to swap between 2 rows in my 2D vector by Entering the size of the vector, the vector elements and 2 integer numbers r1 and r2 represent the rows to be swapped
I really don't know if there is a pre-defined function to do so.
input
3 3
84 87 78
16 94 36
87 93 50
1 2
Output
The array after swapping:
16 94 36
... | Use std::swap(mat[r1-1], mat[r2-1]);
|
66,781,901 | 66,786,136 | Sum two Linked Lists | I have a node like this:
struct ListNode {
int val;
ListNode *next;
ListNode()
: val(0), next(nullptr) {}
ListNode(int x)
: val(x), next(nullptr) {}
ListNode(int x, ListNode *next)
: val(x), next(next) {}
};
And I want to sum two link lists using recursion. I am not sure, bu... | There are several issues:
Your recursion never stops, and this is the cause of the segmentation fault -- at the recursive call you evaluate l1->next, but at a certain point l1 will be a nullpointer, and so you get the exception. The so-called "base case" of the recursion is missing. When both list pointers are null an... |
66,782,197 | 66,782,778 | MFC Tri-state CheckBox — how to change the order of the states? | How to change the order of tri-state MFC CheckBox control?
Now when I click it has the followins states order:
BST_INDETERMINATE > BST_UNCHECKED > BST_CHECKED > cycle
But I need the following:
BST_INDETERMINATE > BST_CHECKED > BST_UNCHECKED > cycle
| Thanks to Adrian Mole for the comment tip!
I forgot to change from BS_AUTO3STATE to BS_3STATE.
The working solution:
void CTestDialog::OnCheckBoxClicked()
{
int state = ((CButton*)GetDlgItem(IDC_CHECKBOX))->GetCheck();
if (state == BST_INDETERMINATE)
((CButton*)GetDlgItem(IDC_CHECKBOX))->SetCheck(BS... |
66,782,291 | 66,782,299 | Can pure virtual function be Variadic function template? | Can i write a class like this:
class Base {
template <typename...Args>
virtual double calculate(const Args&...args) = 0;
};
then i want to write derived class like this:
class Derived1 : public Base {
double calculate(int a) {
}
};
class Derived2 : public Base {
double calculate(int a, int c) {
}
};
if t... | No. Virtual functions can not be templates at all. That applies to any template (variadic or not), and all virtual functions - pure or not.
If you think about it, it makes sense. Template is not a function, it is a template by which compiler will make a function when it is called. A virtual function, on the other hand,... |
66,783,854 | 66,784,021 | How to use std::condition_variable with my own mutex wrapper | I wanted to demonstrate / log some std::mutex behaviour. I would like to log every call to lock() and unlock() (regardless whether they succeed or have to block). Originally, since those methods are not virtual, I tried to wrap the standard std::mutex in the following way, instead of using inheritance:
struct mutex_wra... | std::condition_variable only works specifically with std::unique_lock<std::mutex> -- so you'll probably want to use std::condition_variable_any. This is a generalization of std::condition_variable that can work with any BasicLockable type, such as your mutex wrapper.
Note that it may be a slight pessimization over usi... |
66,783,998 | 66,818,703 | Multiple threads waiting for all to finish till new work is started | I am trying to create a sort of threadpool that runs functions on separate threads and only starts a new iteration when all functions have finished.
map<size_t, bool> status_map;
vector<thread> threads;
condition_variable cond;
bool are_all_ready() {
mutex m;
unique_lock<mutex> lock(m);
for (const auto& [_, stat... | There are several ways to do this.
Easiest in my opinion would be a C++20 std::barrier, which says, "wait until all of N threads have arrived and are waiting here."
#include <barrier>
std::barrier synch_workers(3);
....
void run(const std::function<void(size_t)>& func, size_t id) {
while (true) {
synch_workers.a... |
66,784,011 | 66,784,680 | C++ Winapi - wrapping up a callback of subclass in a class | I wanted to create a class that I will be used to create a static control. The problem is when subclassing the control, the callback should be static which means I won't be able to access non-static variables and function inside the callback.
I've been pulling my hair to make my code works but still no success.
MyClass... | You can use the dwRefData parameter of SetWindowSubclass() to pass the this pointer to the dwRefData parameter of the callback. You can then type-cast that parameter to access non-static members. No need to use GWLP_USERDATA at all (especially since you are not using the callback's lParam correctly when setting GWLP_US... |
66,784,327 | 66,784,418 | Why can I not to readdress pointer within an outer function in C++? | I have a simple code:
void function1(int* A);
void function2(int* A);
int main(int argc, char* argv[]) {
int* A = new int[4];
// Readdressed into function1: A[0] is preserved
A[0] = 21;
function1(A);
cout << "\nA[0] is: " << A[0];
// Result A[0] = 21
// Is not readdressed into function2: ... | Unless you pass a reference, parameters are passed by value. Pointers are no different.
void function1(int* A) {
A = new int[4];
A[0] = 23;
}
void function2(int* A) {
A[0] = 23;
}
function1 assigns a new value to A. However, A is a local variable in function1. Assining 23 to the first element of that new a... |
66,784,474 | 66,814,250 | Constants of a class in C++ | Suppose that I have the following classes in my C++ code
class Test{
double limitsum;
double limitmulti;
public:
void setlimits(double limitsum_,double limitmilti_){limitsum=limitsum_;limitmulti=limitmulti_}
bool checksum(double a, double b){
return(a+b<limitsum);
}
bool checkmu... | According to your last comment, and if I understand what you want, here is my proposition.
#include <iostream>
#include <vector>
#include <stdlib.h> /* srand, rand */
class Test
{
public:
static double limitsum ;
static double limitmulti;
public:
static void setlimits(double limitsum_, double limitmil... |
66,784,603 | 66,784,781 | Expose only class instances in C++ | I'm trying to define a class where explicit instantiation is prohibited.
The user must be able to use only a limited set of instances.
In term of code I'm currently doing something like this:
class Obj
{
private:
int _x;
Obj(int x) : _x() {}
public:
static const Obj obj1;
static const Obj obj2;
};
const Obj O... | Public static members (either functions or objects) are always able to be found during lookup from an instance of that class -- so the only way to avoid it is to not offer these as static members from the type you are providing.
Due to your requirement of keeping Obj's constructor private, we need to use friendship som... |
66,784,843 | 66,785,648 | Handling multiple clients simultaneously in C++ UDP server | I have developed a C++ UDP based server application and I am in the process of implementing code to handle multiple clients simultaneously .
I have the following understanding regarding how to handle multiple clients and want to fill in the knowledge gaps
My step wise understanding is as mentioned below
UDP server lis... |
The clients gets the response and the worker thread terminates.
The worker thread should terminate when it completes processing. There is no practical way for it to wait for an acknowledgement from the client.
The worker thread processes the request and sends the response to the clients IP:port
I think it will be ... |
66,784,976 | 66,785,065 | How to make a count down in C++ | In python the time.sleep() is for count down time before execute next code:
import time
time.sleep(5)
print("something")
So what is the equivalent to that in C++. Sorry for asking this simple question but I am new to C++
| The "sleep_for" allows you to give the time you want to delay, and "sleep_until" allows you to delay until a exact time.
#include
#include
int main() {
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono; // nanoseconds, system_clock, seconds
sleep_for(nanoseconds(10))... |
66,784,977 | 66,785,714 | How can I create a validate function that would validate the input from the user based on the specific input and its defined regular expression? | I am validating user input using Regular Expressions in C++, but the problem I'm facing is that the code is very repetitive. I'd like to have a function that simply takes in the variable to which the user is inputting a value and its defined RE as arguments, validating these inputs and only then allowing the user to mo... |
I'd like to have a function that simply takes in the variable to which the user is inputting a value and its defined RE as arguments, validating these inputs and only then allowing the user to move on to the next input.
Then write that function - you've already done 95% of the work. It would probably look something l... |
66,785,127 | 66,785,218 | How to make max heap filled with std::pair in C++ | We know std::priority_queue can be used to make a max heap. If I put a std::pair into it, it should be ordered according to the std::pair definition by comparing the first element and then the next:
template<class _Ty1,
class _Ty2> inline
constexpr bool operator<(const pair<_Ty1, _Ty2>& _Left,
const pai... | They are ordered. Your IDE is showing you the order of pairs in the vector that underlies your priority queue. See e.g. Wikipedia on how a heap is usually represented in array form to understand why they appear in this exact order. If you actually pop the elements of your queue one by one the will be returned in the co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.