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
|
|---|---|---|---|---|
74,469,980
| 74,470,032
|
How to make concept that checks type equality for any templated type in C++?
|
In C++ you can make concepts that check for specific type equality:
template<typename T> concept Int = std::is_same_v<T, int>;
template<typename T> concept String = std::is_same_v<T, std::string>;
Is it possible to make a concept that checks for type equality of any type, so I could make templates looking something like this:
template<ValidType<int>... Ints> void passInts(Ints... ints) {}
template<ValidType<std::string>... Strings> void passStrings(Strings... strings) {}
That way I would only need to write a single concept checking for type equality. I know I could use conjunction for this but I think concepts are much cleaner.
|
I mean, you could write a concept to do that. Or you could just use std::same_as:
template<std::same_as<int>... Ints> void passInts(Ints... ints)
template<std::same_as<std::string>... Strings> void passStrings(Strings... strings)
When a concept is used against a template parameter pack, it is applied individually to each of the types in the pack.
Of course, this may not quite do what you need. The reason being that same_as is very serious about its name. If you want to invoke perfect forwarding through forwarding references, template argument deduction can start deducing the types as references to T. Which re not the "same_as" T.
So if you want to allow for perfect forwarding, you need a different concept: similar_to. Which sadly is not in the standard library, despite how simple and useful it is:
template<typename T1, typename T2>
concept similar_to = std::same_as<std::remove_cvref_t<T1>, T2>;
Note that this assumes that T2 has no reference or cv qualifiers. You can make a version that removes cvref from both.
Now, you can do this:
template<similar_to<int> ...Ints> void passInts(Ints && ...ints)
template<similar_to<std::string> ...Strings> void passStrings(Strings && ...strings)
And now you get perfect forwarding back.
|
74,470,769
| 74,470,976
|
Verify whether the key exists in a map and access the iterator in the caller
|
I am trying to know in the caller whether the value in the underlying map exists, and if so, return a reference/iterator to it since the caller needs its access.
Typically you check whether the element exists in a map by verifying whether the returned iterator == map.end(), but here there's no way in the caller to tell that
class A
{
std::unordered_map<int,int> m = { {5,100} };
public:
std::unordered_map<int,int>::iterator get(int key)
{
std::unordered_map<int,int>::iterator it = m.find(key);
return it;
}
};
int main()
{
A a;
auto keyIter = a.get(5);
// if keyIter is not m.end() ...
// if keyIter is in m ...
}
|
Why return an iterator at all? Surely the right way would be to return the int if it exists? If so you can use optional to indicate if it is valid or not:
std::optional<int> get(int key) {
std::unordered_map<int,int>::iterator it = m.find(key);
if (it != m.end())
return it->second;
return std::nullopt;
}
Usage would then be nice and clean:
auto value = a.get(5);
if (value) {
use_value(*value);
} else {
std::cout << "Key 5 is not in the map\n";
}
|
74,470,941
| 74,471,246
|
Question on basic_string.h implementation
|
I was looking at the basic_string.h implementation to understand more and try to compile it in a separate namespace. I have the below compile error and was confused. I am using gcc compiler 12.1
basic_string.h: error: wrong number of template arguments (1, should be 3)
operator==(const basic_string<_CharT>& __lhs,
The template for basic_string class has 3 arguments
// 21.3 Template class basic_string
template <typename _CharT, typename _Traits, typename _Alloc>
class basic_string {
typedef typename _Alloc::template rebind<_CharT>::other _CharT_alloc_type;
However, in later part of the code, I saw that when they try to overload the operator==, they use basic_string with only 1 argument, i.e. <_CharT>.
template <typename _CharT>
inline typename __gnu_cxx::__enable_if<std::__is_char<_CharT>::__value,
bool>::__type
operator==(const basic_string<_CharT>& __lhs,
const basic_string<_CharT>& __rhs) _GLIBCXX_NOEXCEPT {
return (__lhs.size() == __rhs.size() &&
!std::char_traits<_CharT>::compare(__lhs.data(), __rhs.data(),
__lhs.size()));
}
How did it work in the std namespace and not working in my own namespace?
|
The file you are referencing is <bits/basic_string.h> in the standard library path of the libstdc++ standard library implementation.
As you are saying it defines std::basic_string without providing default arguments to any of its three template parameter.
However the standard requires that the second and third be defaulted to std::char_traits<CharT> and std::allocator<CharT> respectively where CharT is the first template parameter.
So std::basic_string<CharT> should be just fine. It should be the same as std::basic_string<CharT, std::char_traits<CharT>, std::allocator<CharT>>.
Libstdc++ is implementing this requirement by including another file <bits/stringfwd.h> at the top of the <bits/basic_string.h> file. In this file std::basic_string is forward declared with the default arguments provided as required above.
You probably did not correctly copy the necessary content from this header.
But even when copying all necessary declarations, as I already pointed out in my comment, there won't be any guarantee that what you are trying to do will work anyway. The implementation may assume that it is located in the std namespace. It may also use macros, pragmas or compiler builtins that only work as intended in the standard library implementation headers. And in user code all identifiers starting with an underscore followed by an upper-case letter or containing a double underscore may not be used. They are reserved specifically to the standard library and compiler implementation.
|
74,471,107
| 74,471,145
|
How to round in functions
|
void isRight(float sideA, float sideB, float sideC){
float aSquared = sideA * sideA;
float bSquared = sideB * sideB;
float cSquared = sideC * sideC;
round(aSquared);
round(bSquared);
round(cSquared);
if (aSquared + bSquared == cSquared || cSquared + bSquared == aSquared || aSquared + cSquared == bSquared){
cout << "This is a right triangle" << endl;
}
}
int main() {
float sideA, sideB, sideC;
cout << "Enter the lengths of the three sides of a triangle -- ";
cin >> sideA >> sideB >> sideC;
isRight(sideA,sideB,sideC);
}
}
I have this program that checks side of my triangle and say if it s a right triangle.it works when I have whole numbers like 3 5 4 it gives me the message that it is a right triangle. But if put 1 1.4142 1, it does not give me the message, which is weird because the 1,4142 squared is equal to 2 which is the same of 1 and 1. can someone catch why this is happening. I am guessing its because its not rounding up but I have the round function
|
This is happening because of Floaing point precision loss.
C++ built-in floating point types are finite in precision. double is usually implemented as IEEE-754 double precision, meaning it has 53 bits of mantissa (the "value") precision, 11 bits of exponent precision, and 1 sign bit.
To solve this, you can do the following instead of ==:
bool approximatelyEqual(float a, float b, float epsilon)
{
return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
bool definitelyGreaterThan(float a, float b, float epsilon)
{
return (a - b) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
bool definitelyLessThan(float a, float b, float epsilon)
{
return (b - a) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
Note: here, epsilon is the floating point error tolerance value (e.g. 0.000001, 0.0000001, etc)
You can read What Every Programmer Should Know About Floating-Point Arithmetic for more information on floating-point formats and their inaccuracies.
|
74,471,983
| 74,472,105
|
How can we declare lvalue inplace while calling a function with lvalue reference parameter?
|
If I have a function like this:
int calc(const DataVec& data_vec, int& sub_sum);
how can I call that without a explicit lvalue definition of type int?
auto calc_result = calc(data_vec, int()); // error, int() is not a lvalue
Below is a valid form:
int _; // not interested
auto calc_result = calc(data_vec, _);
|
This can be solved with function overloading. Like
int calc(const DataVec& data_vec);
Your overloaded function could be a simple wrapper around your dummy-int variable workaround:
int calc(const DataVec& data_vec)
{
int dummy = 0;
return calc(data_vec, dummy);
}
Please note that this might be a suitable workaround to the problem. But it might as well be a workaround for a problem that doesn't really exist, and and there shouldn't really be any workarounds. Perhaps there is a very good reason for the original calc functions second argument being a non-const lvalue reference?
|
74,472,175
| 74,472,235
|
how to run Bool function if if statement is true
|
bool isTriangle(double sideA, double sideB, double sideC){
if(sideA + sideB > sideC && sideA + sideC > sideB && sideB + sideC > sideA){
return true;
}else{
return false;
}
}
int main() {
double sideA, sideB, sideC;
cout << "Enter the lengths of the three sides of a triangle -- ";
cin >> sideA >> sideB >> sideC;
if (&isTriangle){
if(sideA != sideB && sideB != sideC){
cout << "This is a scalene";
}
isEquilateral(sideA, sideB, sideC);
isIsosceles(sideA, sideB, sideC);
isRight(sideA,sideB,sideC);
cout << "Its perimeter is " << per << endl;
}
if(!&isTriangle){
cout << "This is not a triangle" << endl;
}
}
How can I run code when an if statement inside the bool function is true.I have my bool function and it test the triangle sides and checks if it is a triangle, if it is, it returns true, if not it returns false. If it's true I want to run my other functions, if it's not a triangle I just want to display a message.
|
This
if (&isTriangle){
should be this
if (isTriangle(sideA, sideB, sideC)){
When you call a function, you use the name of that function followed by parentheses () and you put the parameters that the function requires inside the parentheses separated by commas.
Some other suggestions.
If you want to test something and do one thing if it is true and another thing if it is false. Then the way to do this is with if ... else .... Like this
if (isTriangle(sideA, sideB, sideC)) {
...
}
else {
...
}
It's not so good to use two if ... and repeat the test, like you are doing
if (isTriangle(sideA, sideB, sideC)) {
...
}
if (!isTriangle(sideA, sideB, sideC)) { // repeated test
...
}
When you have code like this if (something) return true; else return false; you can skip the if statement and just say return something;. In other words there's no need to say 'if something is true then return true and if something is false return false' you can just say 'return something'. So this code
if(sideA + sideB > sideC && sideA + sideC > sideB && sideB + sideC > sideA){
return true;
}else{
return false;
}
can be rewritten more simply as
return sideA + sideB > sideC && sideA + sideC > sideB && sideB + sideC > sideA;
|
74,472,823
| 74,597,670
|
Which Visual Studio project settings affect the list of DLLs imported at the start of the program?
|
There are two PCs with Visual Studio 2017 installed. I'm running a simple program on both of them, one that lists the name of modules (exes/DLLs) inside its own process.
But I get wildly different results. On one PC, I only get 7 modules:
Lab7_1.exe
ntdll.dll
KERNEL32.DLL
KERNELBASE.dll
MSVCP140D.dll
VCRUNTIME140D.dll
ucrtbased.dll
On the other, I get whopping 31 modules. The full list includes, for example, user32.dll, which my sample program isn't using (it's a console app, not a GUI app).
So the question is: what exactly affects the list of DLLs imported by default? Debug/Release and x86/x64 switches produces some difference, but nothing that drastic.
Differences between platform tools versions (and corresponding versions of MS VC++ Redist) I can understand, but why are different system DLLs being imported as well?
I'm unsure where else to look.
Context: it's a part of an assignment. On of those PCs is mine, the other is where the students work. The assignment goes like this "We have this set of modules by default, now we use MessageBoxA(), and we see that more modules are imported, user32.dll among them". Which doesn't quite work if user32.dll is always imported by default.
Since the behaviour is vastly different, and I can't reproduce it on my PC, it's hard to adapt the assignment so the students can see import mechanics at work.
Sample program code:
#include <iostream>
#include <vector>
#include <string>
#include <Windows.h>
#include <Psapi.h>
using namespace std;
#pragma comment(lib, "psapi.lib") //needed for MS VS 2010
void EnumerateModules(vector<HMODULE>& modules)
{
HANDLE me = GetCurrentProcess();
DWORD needed_size = 0;
while (true)
{
DWORD actual_size = modules.size() * sizeof(HMODULE);
EnumProcessModules(
me, //which process
modules.data(), //where to put the module handlers
actual_size, //allocated buffer size
&needed_size //desired buffer size
);
if (needed_size != actual_size)
modules.resize(needed_size / sizeof(HMODULE));
else
break;
}
}
string ModuleName(HMODULE module)
{
HANDLE me = GetCurrentProcess();
string buffer(FILENAME_MAX, 0);
DWORD real_length = GetModuleBaseNameA(
me, //which process
module, //which module
&buffer[0], //where to put the name
buffer.size() //size of the name buffer
);
if (real_length > 0)
return buffer.substr(0, real_length);
buffer = "";
return buffer;
}
int main(int argc, char* argv[])
{
setlocale(0, "");
vector<HMODULE> modules;
EnumerateModules(modules);
cout << modules.size() << " modules:" << endl;
for (size_t i = 0; i < modules.size(); i++)
{
string name = ModuleName(modules[i]);
cout << name.c_str() << endl;
}
return 0;
}
|
Okay, turns out it's not related to Visual Studio settings. I compiled the sample code on one machine, ran in on the other, and got the same result as if I compiled the code there. So it's either Windows version (7 vs 10) or MS VS Redistributable version (though I think both projects used v140). In either case, I can't reproduce the behaviour on my machine unless I'm willing to set up a VM.
|
74,473,008
| 74,474,292
|
Why is std::forward necessary for checking if a type can be converted to another without narrowing in C++20
|
To make a concept checking if a type can be converted without narrowing to another, it is proposed here to make it using std::forward and std::type_identity_t like this:
template<class T, class U>
concept __construct_without_narrowing = requires (U&& x) {
{ std::type_identity_t<T[]>{std::forward<U>(x)} } -> T[1];
};
I understand from it why something like this:
To{std::declval<From>()}
gives incorrect results, but when i try to simplify it using another idea in the paper, writing just
template <typename From, typename To>
concept WithoutNarrowing =
requires (From x) {
{(To[1]){x}}
->std::same_as<To[1]>;
};
It seems to give the same results. What circumstances have to occur for it to give different result? Or is it equivalent? For what reason is std::forward used here?
|
This is the usual approach for type traits like this that involve some kind of function/constructor argument.
U is the type from which T is supposed to be constructed, but if we want to discuss the construction we also need to consider the value category of the argument. It may be an lvalue or a rvalue and this can affect e.g. which constructor is usable.
The idea is that we map the rvalue argument case to a non-reference U or rvalue reference U and the lvalue argument case to a lvalue reference U, matching the mapping of expressions in decltype and of return types with value categories in function call expressions.
Then, by the reference collapsing rules, U&& will be a lvalue reference if the constructor argument is a lvalue and otherwise a rvalue reference. Then using std::forward means that the actual argument we give to the construction will indeed be a lvalue argument when U was meant to represent one and a rvalue argument otherwise.
Your approach using {(To[1]){x}} doesn't use the forwarding and so would always only test whether construction from a lvalue can be done without narrowing, which is not what is expected if e.g. U is a non-reference.
Your approach is further incorrect because (To[1]){x} is not valid syntax in standard C++. If X is a type you can have X{x} or (X)x, but not (X){x}. The last syntax is part of C however and called a compound literal there. For that reason a C++ compiler may support it as an extension to C++. That's why the original implementation uses the round-about way with std::type_identity_t.
The implementation seems to also be written for an earlier draft of C++20 concepts. It is now not possible to use types to the right of -> directly for a requirement. Instead a concept, i.e. -> std::same_as<T[1]>, must be used as in your suggested implementation.
|
74,473,260
| 74,474,056
|
Do ASIOs io_context.run() lock the thread into busy waiting
|
I think a straightforward question that i cant seem to find any information on. When calling ASIOs io_context.run(), if there is at that moment nothing yet to read/write asynchronously, does asio do busy waiting with that thread or does it do something more clever where the thread can be released and used in other parts of the application or OS?
I looked into the code but its not very clear to me what the answer is. I do see usage of conditional variables in some places so i can only presume that the run call is not busy waiting if it doesnt have to be.
I ask because in our case, we would like to maximise thread efficiency so it was suggested to place a thread sleep inside a recursive async read handler in case asio is busy waiting. We dont get that much network activity for a single thread to be used maximally.
|
It's not busy-waiting. This is documented here: The Proactor Design Pattern: Concurrency Without Threads
It highlights what underlying API's are preferred depending on platforms:
On many platforms, Boost.Asio implements the Proactor design pattern in terms of a Reactor, such as select, epoll or kqueue.
And
On Windows NT, 2000 and XP, Boost.Asio takes advantage of overlapped I/O to provide an efficient implementation of the Proactor design pattern.
Q. it was suggested to place a thread sleep inside a recursive async read handler in case asio is busy waiting
Don't do that. Keeping handlers short will allow you to multiplex all IO on a single service. If you do blocking work, consider posting it to a separate thread (pool).
|
74,473,410
| 74,473,556
|
Unordered map hash function
|
#include <iostream>
#include <unordered_map>
#include <utility>
#include <cmath>
#include <stdint.h>
template <class T>
struct Vec2
{
T x, y;
Vec2() : x(0) , y(0) { };
Vec2(T xn, T yn) : x(xn), y(yn) { };
bool operator==(const Vec2& vec) const
{
return (x == vec.x) and (y == vec.y);
}
};
struct HashVec2int
{
const uint32_t maximum;
// HashVec2int(const uint32_t& m) : maximum(m) { }
std::size_t operator()(const Vec2<int>& vec) const
{ return (vec.x * maximum) + vec.y; }
};
int main() {
typedef Vec2<int> iVec2;
std::unordered_map<std::pair<iVec2, iVec2>,
float, HashVec2int{300}> umap;
umap[std::make_pair(iVec2(1, 2), iVec2(2, 3))] = 3.14f;
std::cout << umap[std::make_pair(iVec2(1, 2), iVec2(2, 3))];
return 0;
}
I want to initialize a hash function with a maximum x value to hash my implementation of vector.
I changed the struct to a class a couple of times and even marked maximum manually inside of HashVec2int. It gave me cryptic errors.
.\main.cpp:35:32: error: type/value mismatch at argument 3 in template parameter list for 'template<class _Key, class _Tp, class _Hash, class _Pred, class _Alloc> class std::unordered_map'
float, HashVec2int{300}> umap;
^
.\main.cpp:35:32: note: expected a type, got 'HashVec2int{300u}'
.\main.cpp:37:6: error: no match for 'operator[]' (operand types are 'int' and 'std::pair<Vec2<int>, Vec2<int> >')
umap[std::make_pair(iVec2(1, 2), iVec2(2, 3))] = 3.14f;
^
.\main.cpp:39:19: error: no match for 'operator[]' (operand types are 'int' and 'std::pair<Vec2<int>, Vec2<int> >')
std::cout << umap[std::make_pair(iVec2(1, 2), iVec2(2, 3))];
^
I followed cppreference tutorials on how to create a modified hash function.
|
You have a map with keys of pairs of iVecs but your hash is for single iVecs, that doesnt match. Though this will only be the next error you will be getting after fixing the current one.
It seems you try to pass an instance HashVec2int{300} as template argument when a type is expected.
If maximum does not change (it should not for the hash to be consistent) you can do it like this:
template <uint32_t maximum>
struct HashVec2int
{
std::size_t operator()(const Vec2<int>& vec) const
{ return (vec.x * maximum) + vec.y; }
};
int main() {
typedef Vec2<int> iVec2;
std::unordered_map<iVec2,
float, HashVec2int<200>> umap;
umap[iVec2(1, 2)] = 3.14f;
std::cout << umap[iVec2(1, 2)];
return 0;
}
If you do not want to make HashVec2int a template you can still use it, then use its type Hashvec2Int as argument for the unordered map template and pass an instance, eg HashVec2Int{200}, to one of the constructors that takes a hash instance: https://en.cppreference.com/w/cpp/container/unordered_map/unordered_map
|
74,473,588
| 74,473,718
|
removing spaces - pass by reference
|
prompt - c++
Write a program that removes all spaces from the given input.
Ex: If the input is: "Hello my name is John." the output is:
HellomynameisJohn.
Your program must define and call the following function. The function should return a string representing the input string without spaces.
void RemoveSpaces(string &userString)
issue - i believe my code is correct; i'm just not very clear on the concept of pass by reference so my code is wrong in terms of my assignment. that's why my output still shows up as string with spaces in my submission.
how would i write this using pass by reference?
my code -
#include <iostream>
using namespace std;
void RemoveSpaces ( string &userString )
{
unsigned int i ;
for ( i = 0 ; i < userString.size() ; i ++ )
{
if ( userString.at(i) != ' ' )
{
cout << userString.at(i) ;
}
}
}
int main() {
string userInputString ;
getline ( cin, userInputString );
RemoveSpaces ( userInputString ) ;
cout << userInputString ;
return 0;
}
for pass by reference i had thought that userString would be "updated" in the function and output as the updated version?
|
It seems to be a common newbie confusion. Printing gets confused with other concepts. If a function prints something, then the function is 'returning' what is printed. This is completely untrue, printing is printing, nothing else.
If you want to write a function that removes spaces from a string, then that is what the function must do. Somehow a new string without the spaces must be created. How that function returns the modified string is a side issue.
Here's a function that removes spaces from a string.
void RemoveSpaces ( string &userString )
{
string temp;
for (size_t i = 0 ; i < userString.size() ; i ++ )
{
if (userString.at(i) != ' ' )
temp.push_back(userString.at(i));
}
userString = temp;
}
This function works by looking for the non-spaces in userString and adding them to a new string temp. This is the string without spaces. Then at the end of the function it assigns this string back to userString. Because userString has been passed by reference this assignment modifies userInputString in main. That's the meaning of pass by reference. Changes to userString actually change the string that is being referred to.
It is possible to write a function that modifies userString directly, but that is more complicated code, so I chose to do it this way with a second string temp.
|
74,474,201
| 74,475,662
|
GCC and Clang seem not to obey the overload resolution in the allocation function call
|
Consider this example
#include <iostream>
struct A{
void* operator new(std::size_t N, std::align_val_t){ // #1
return malloc(sizeof(char)* N);
}
};
int main(){
auto ptr = new A; // #2
}
Both GCC and Clang complain that
<source>:9:17: error: no matching function for call to 'operator new'
auto ptr = new A;
^
<source>:4:11: note: candidate function not viable: requires 2 arguments, but 1 was provided
void* operator new(std::size_t N, std::align_val_t){
^
1 error generated.
However, [expr.new] p19 says
Overload resolution is performed on a function call created by assembling an argument list.
The first argument is the amount of space requested, and has type std::size_t.
If the type of the allocated object has new-extended alignment, the next argument is the type's alignment, and has type std::align_val_t.
If the new-placement syntax is used, the initializer-clauses in its expression-list are the succeeding arguments. If no matching function is found then
if the allocated object type has new-extended alignment, the alignment argument is removed from the argument list;
otherwise, an argument that is the type's alignment and has type std::align_val_t is added into the argument list immediately after the first argument;
and then overload resolution is performed again.
The found candidate for the allocation function calling in the new expression at #2 is #1. For the first time, the assembling argument list is sizeof(A), which cannot make #1 a matching function, then according to the rule, the assembling arguments will be sizeof(A),std::align_val_t(alignof(A)), which can make #1 a matching function. Also, it's a typical example recorded in [expr.new] p20
new T results in one of the following calls:
operator new(sizeof(T))
operator new(sizeof(T), std::align_val_t(alignof(T)))
Why do GCC and Clang reject this example? Is this defect of GCC and Clang? Or, Do I misunderstand something?
|
At present the only major compiler that implements CWG 2282 is MSVC. I'm not aware of any current effort or feature requests for GCC or clang.
Also, I don't believe the __cpp_aligned_new feature test macro has been updated for CWG 2282, so you'll need to use old-fashioned compiler version checking to determine whether the feature is available.
|
74,474,270
| 74,474,364
|
When to use std::numeric_limits<double>::espsilon() instead of DBL_EPSILON
|
I understood that std::numeric_limits::espsilon() and DBL_EPSILON should deliver the same value but are defined in different headers, limits, and cfloat. Which makes std::numeric_limits::espsilon() a c++ style way of writing and DBL_EPSILON the c style.
My question is if there is any benefit in using std::numeric_limits::espsilon() over DBL_EPSILON in c++ project? Aside from a clean c++ coding style. Or did I understand this completely wrong?
|
Here on this page https://en.cppreference.com/w/cpp/types/numeric_limits you can find tables of what are the C marco equivalents of the std::numeric_limits.
They are equivalents, so for any pair of std::limits function/constant and C macro you find in the table, they can be interchanged.
The big difference is in generic code:
template <typename T>
void foo() {
std::cout << std::numeric_limits<T>::epsilon();
}
Doing the same with C macros would require to write much more code. Also any opportunity to not use a macro is a good one.
|
74,474,371
| 74,474,681
|
Concept that requires a certain return type of member
|
I have some trouble getting started with C++20 concepts. I want to define a concept that requires a class to have a member called count_ that must be of type int:
#include <concepts>
template <typename T>
concept HasCount = requires(T thing) {
{ thing.count_ } -> std::same_as<int>;
};
The following struct should satisfy this concept:
struct BaseTableChunk {
BaseTableChunk* next_;
int count_ = 0;
int data_[1000];
};
Then, the following code does not compile:
template <HasCount Chunk>
class BaseTable {
void doSomething();
};
int main() {
BaseTable<BaseTableChunk> table{};
return 0;
}
The compiler gives the following error:
note: constraints not satisfied
In file included from /usr/include/c++/10/compare:39,
from /usr/include/c++/10/bits/stl_pair.h:65,
from /usr/include/c++/10/bits/stl_algobase.h:64,
from /usr/include/c++/10/bits/char_traits.h:39,
from /usr/include/c++/10/ios:40,
from /usr/include/c++/10/ostream:38,
from /usr/include/c++/10/iostream:39,
from Minimal2.cxx:1:
/usr/include/c++/10/concepts:57:15: required for the satisfaction of ‘__same_as<_Tp, _Up>’ [with _Tp = int&; _Up = int]
/usr/include/c++/10/concepts:62:13: required for the satisfaction of ‘same_as<int&, int>’
/usr/include/c++/10/concepts:57:32: note: the expression ‘is_same_v<_Tp, _Up> [with _Tp = int&; _Up = int]’ evaluated to ‘false’
57 | concept __same_as = std::is_same_v<_Tp, _Up>;
As I understand it, thing.count_ is evaluated to return an int& instead of an int, which is not what I'd expect.
Should I instead test for { thing.count_ } -> std::same_as<int&>? (Which then does compile.) That seems rather counter-intuitive to me.
|
If count_ is a member of thing with declared type int, then the expression thing.count_ is also of type int and the expression's value category is lvalue.
A compound requirement of the form { E } -> C will test whether decltype((E)) satisfies C. In other words, it tests whether the type of the expression E, not the type of the entity that E might name, satisfies the concept.
The type of the expression as obtained by decltype((E)) translates the value category to reference-qualification of the type. Prvalues result in non-references, lvalues in lvalue references and xvalues in rvalue references.
So, in your example, the type will be int& but the concept std::same_as requires strict match of the type, including its reference-qualification, making it fail.
A simple solution would be to just test against int&:
{ thing.count_ } -> std::same_as<int&>;
A similar solution as mentioned also in the question comments is since C++23:
{ auto(thing.count_) } -> std::same_as<int>
auto is deduced to int and the functional-style cast expression int(...) is always a prvalue, so that it will never result in a reference-qualified type.
Another alternative is to write a concept to replace std::same_as that doesn't check exact type equality but applies std::remove_reference_t or std::remove_cvref_t to the type first, depending on how you want to handle const-mismatch. Notably, the first solution will not accept a const int member or const-qualified T with int member, while the second one will (because auto never deduces a const).
However, you should be careful here if you intend to check that thing has a member of type int exactly. All of the solutions above will also be satisfied if it has a thing member of type reference-to-int.
Excluding the reference case cannot be done with a compound requirement easily, but a nested requirement may be used instead:
template <typename T>
concept HasCount = requires(T thing) {
requires std::same_as<decltype(thing.count_), int>;
};
The nested requirement (introduced by another requires) checks not only validity of the expression but also whether it evaluates to true. The difference in the check here is that I use decltype(thing.count_) instead of decltype((thing.count_)). decltype has an exception when it names a member directly through a member access expression (unparenthesized). In that case it will produce the type of the named entity, not of the expression. This verifies that count_ is a int, not a int&.
There are also further edge cases you should consider if T is const-qualified or a reference type. You should carefully consider under which conditions exactly the concept should be satisfied in these cases. Depending on the answer the suggested solutions may or may not be sufficient.
And as another edge case you need to consider whether you really want to accept any member or only non-static ones. All of the solutions above assume that you will accept a static member as well.
Also, you need to consider whether a member inherited from a base class should be accepted. All of the suggested solutions above do accept them.
All of the above solutions also assume that the member should be accepted only if it is public. The check in the concept is done from a context not related to any class, so accessibility based on context doesn't work anyway, and there probably is no reason to accept a private member that then wouldn't actually be usable in the function that is constrained by the concept.
|
74,474,636
| 74,475,517
|
Why is only the first Child Process printing something out?
|
The program I am working on is called myfile - It should find a file in a certain searchpath. You should also be able to search for multiple files and if so, I MUST create multiple child processes with fork(). The problem is, i dont get the expected outcome printed out. If I am searching for multiple files, only the first file gets "returned". I think it has something todo with the second for in the else statement. For debugging I am printing out every PID of the child processes. Is the problem maybe that the child processes are working with the same variables at the same time?
The Code:
`
#include<iostream>
#include<dirent.h>
#include<string.h>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
using namespace std;
int main(int argc, char** argv)
{
struct dirent *d;
DIR *dr;
dr = opendir(argv[1]);
pid_t pid;
int numberOfFiles = argc - 2;
if(dr!=NULL){
if(numberOfFiles == 1){
// normal search without fork
for(d=readdir(dr); d!=NULL; d=readdir(dr)){
if(strcmp(d->d_name, argv[argc-1]) == 0){
cout << "<" << getpid() << ">: " << argv[argc-1] << ": <" << realpath(argv[argc-1], NULL) << ">" <<endl;
}
}
}else{
// search with fork
for(int i = 2; i < argc; i++){
if(fork() == 0){
cout << "Current PID: " << getpid() << " " << argv[i] <<endl;
for(d=readdir(dr); d!=NULL; d=readdir(dr)){
if(strcmp(d->d_name, argv[i]) == 0){
cout << "Current i=" << i << " "<< "<" << getpid() << ">: " << argv[i] << ": <" << realpath(argv[i], NULL) << ">" <<endl;
}
}
exit(0);
}
}
for(int i=0; i < numberOfFiles; i++){
wait(NULL);
}
}
}else
cout<<"\nError Occurred!"<<endl;
cout<<endl;
return 0;
}
`
Screenshot of output in terminal:
The problem is, i dont get the expected outcome printed out. If I am searching for multiple files, only the first file gets "returned". I think it has something todo with the second for in the else statement. For debugging I am printing out every PID of the child processes. Is the problem maybe that the child processes are working with the same variables at the same time?
|
Looks like a problem with opendir, readdir, and reusing variables. I cut your program down to:
int main(int argc, char **argv)
{
struct dirent *d;
DIR *dr;
dr = opendir(argv[1]);
for (int i = 2; i < argc; i++)
{
if (fork() == 0)
{
cout << "Current PID: " << getpid() << " " << argv[i] << endl;
for (d = readdir(dr); d != NULL; d = readdir(dr))
{
cout << getpid() << "\t" << d->d_name << endl;
}
exit(0);
}
}
for (int i = 0; i < argc - 2; i++)
wait(NULL);
}
And got this output (from ./testfork ../bla 1 2):
Current PID: 17197 1
Current PID: 17198 2
17198 test.txt
17198 ..
17198 .
Which shows that once one process has read to end with readdir, then the other gets nothing. However, if I move the call to opendir to after the fork:
int main(int argc, char **argv)
{
struct dirent *d;
DIR *dr;
for (int i = 2; i < argc; i++)
{
if (fork() == 0)
{
dr = opendir(argv[1]); // <- Here
cout << "Current PID: " << getpid() << " " << argv[i] << endl;
for (d = readdir(dr); d != NULL; d = readdir(dr))
{
cout << getpid() << "\t" << d->d_name << endl;
}
exit(0);
}
}
for (int i = 0; i < argc - 2; i++)
wait(NULL);
}
The the output becomes:
Current PID: 17751 1
17751 test.txt
17751 ..
17751 .
Current PID: 17752 2
17752 test.txt
17752 ..
17752 .
I don't quite understand why this happens, since the way fork works should ensure that each process get their own copy of the memory (though possibly only after writing to it). So when one process modifies dr, then that change should not be reflected in the other processes.
Perhaps it is due to dr actually being changed through system calls (by way of readdir), and not by the process directly?
|
74,474,821
| 74,475,621
|
C++: Copy the vector of pointers to arrays, to Eigen::ArrayXd
|
I have std::vector<double *> x, in which each elements points to C-style double array. The values of double arrays are changing with each iteration of my program. I would like to create a copy of them into Eigen::ArrayXd x_old so I can compute a difference with new values. I have tried to use Eigen::Map but it copied only one array and they were still connected memory-wise, so it was not a copy technically. Now I tried to memcpy it, but I am getting only the first array. Thank you for your help
std::vector<double *> x;
x.push_back( new double[2]{1, 2} );
x.push_back( new double[2]{3, 4} );
Eigen::ArrayXd x_old(4);
memcpy(x_old.data(), *x.data(), 4*sizeof(double));
|
The problem with memcpy(x_old.data(), *x.data(), 4*sizeof(double)); is that since you manually allocated memory for each elements of the vector, the data underneath aren't contiguous anymore, ie 2 is not followed by 3.(The locations of the pointers are contiguous, but the arrays they are pointing to are not)
So when you put them into x_old, you can't get them as a contiguous memory. Instead you need to add each elements of the vector separately:
memcpy(x_old.data(), x[0], 2 * sizeof(double));
memcpy(x_old.data() + 2, x[1], 2 * sizeof(double));
Or write a for-loop:
for(std::size_t s = 0; const auto& data: x)
{
memcpy(x_old.data() + s, data, 2 * sizeof(double));
s += 2;
}
Sidenote, *x.data() is the same as saying x[0].
|
74,475,178
| 74,475,767
|
Passing a reference to an abstract class object
|
I have an abstract syntax tree class which uses the visitor pattern. All constructors and the visit functions take in a reference to the abstract node 'ASTNode' or its derived classes.
class ASTNode {
public:
virtual void accept(ASTVisitor& visitor) = 0;
};
class NameNode : public ASTNode {
public:
NameNode(std::string name) : name(name) { }
void accept(ASTVisitor& visitor) override;
std::string name;
};
class ListNode : public ASTNode {
public:
ListNode(ElementSptr list) : list(list) { }
void accept(ASTVisitor& visitor) override;
ElementSptr list;
};
class BinaryOperator : public ASTNode {
public:
BinaryOperator(std::string kind, ASTNode& left, ASTNode& right)
: kind(kind), left(left), right(right) { }
void accept(ASTVisitor& visitor) override;
std::string kind;
ASTNode& left;
ASTNode& right;
};
class ASTVisitor {
public:
virtual void visit(ASTNode& node) = 0;
virtual void visit(NameNode& name) = 0;
virtual void visit(ListNode& list) = 0;
virtual void visit(BinaryOperator& bOp) = 0;
virtual void visit(UnaryOperator& uOp) = 0;
};
I have a separate class that builds the actual tree and this is the function that does it. But the thing is, I can't create ASTNode root, left, right because it is abstract of course. When I add '&' to the definitions, it says that the variables 'root' requires initializer. I tried using pointers in this function to fix that and it did, however, if every child of the root is a pointer to an ASTNode, the existing tree will not work with it since it takes in references. So is there anyway to make this function work without pointers? :
The objective of this function is to return only the root node to the calling class and the calling class should then be able to do operations on its children:
ASTNode& TreeBuilder::buildTree(std::string expression){
std::vector<std::string> tokens = split(expression);
std::deque<ASTNode&> nodeStack;;
std::deque<std::string> operatorStack;
ASTNode root;
ASTNode& left;
ASTNode& right;
//generates tree from tokens
return root;
}
|
Since ASTNode is purely virtual you cannot construct an instance of it, moreover you should not use value semantics when dealing with polymorphic types, because of slicing.
Secondly in the example shown you return a reference to a local variable.
You should either use pointers (as you mentioned) and construct the tree on the heap. Or you pass a root node to the function by reference:
void TreeBuilder::buildTree(ASTNode& root, std::string expression){
//generates tree from tokens
}
|
74,475,436
| 74,478,041
|
mkTime() function does not pick correct timezone c++
|
I am getting an input date from user and convert it into tm struct, (setting is_dst, timezone and gmtoff parameters of tm struct using local time), but when I am using mkTime to get epoch value it changes the timezone and gmtOffset property of tm struct and return the wrong offset value.
tm tmStartDateTime = {};
string dateString = inputDate;
if (myclass::tryParseString(inputDate, "%Y/%m/%d %H:%M:%S", tmStartDateTime))// converting string date to tm
{
struct timespec now = {0};
clock_gettime(CLOCK_REALTIME, &now);
tm *nowStruct = localtime(&now.tv_sec);
// setting isdst, gmtoff and timezone using localtime
tmStartDateTime.tm_isdst = nowStruct->tm_isdst;
tmStartDateTime.tm_gmtoff = nowStruct->tm_gmtoff;
tmStartDateTime.tm_zone = nowStruct->tm_zone;
tm bmStartDate = {};
bmStartDate = tmStartDateTime;
StartDateTimeEpoch = mktime(&bmStartDate);
}
for e.g. if user gives a date 01/01/1970 00:00:00 and machine timezone is set to Europe/London, then tm struct gmtoffset value changes to 3600 and timezone changes to BST whereas the machine timezone is GMT with 0 gmtoffset as daylight saving is ended on 30th oct 2022. Why and How mktime is changing timezone and gmtoffset value of tm struct. (Note: TZ variable of machine is set to empty string, i have also change that to Europe/London but with no luck)
|
localtime() is using the DST setting for the time you passed to it, not the current time when the function is called. DST was in effect in the UK on 1 Jan 1970, so it will return summer time regardless of whether DST is in effect today.
|
74,475,799
| 74,475,945
|
SMBUS undefined reference
|
I'm trying to make simple program in c++ to read from SMBus, but can't even build program sample.
I'm building with gcc(9.4.0) on Ubuntu 20.04.5 LTS.
I've installed
libi2c-dev
i2c-tools
Code:
#include <cstdio>
extern "C" {
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>
}
#include <fcntl.h>
#include <sys/ioctl.h>
int main(int argc, char ** argv)
{
int file;
int adapter_nr = 6;
char filename[20];
snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
file = open(filename, O_RDWR);
if (file < 0) {
return(1);
}
int addr = 0x0b;
if (ioctl(file, I2C_SLAVE, addr) < 0) {
return(1);
return(1);
}
__u8 reg = 0x0d;
__s32 res;
char buf[10];
res = i2c_smbus_read_word_data(file, reg);
return 0;
}
Build command: gcc -li2c test_inc.cpp
but I'm getting following error:
test_inc.cpp:(.text+0xb9): undefined reference to `i2c_smbus_read_word_data'
collect2: error: ld returned 1 exit status
Linking i2c is passed as argument, and shared object exists
libi2c
Can anyone help me to solve this riddle ?
I tried to update apts and reinstalled all packages I also added "-I path_to_so_file" to gcc
|
The order of the source file and the library is relevant. The following command should work:
gcc test_inc.cpp -li2c
|
74,476,213
| 74,490,320
|
c++ convert fmt::format_string<Args...>to std::string_view
|
I'm currently struggling to convert fmt::format_string<Args...>to a std::string_view.
The idea: I would like to create a fucntion with can be called from an ISR and task context. However in an ISR no dynamic memory allocation is allowed. That's why i cannot call fmt::fomat() in this case. However I'm getting a strange compiler error
<source>(67): error C7595: 'fmt::v9::basic_format_string<char>::basic_format_string': call to immediate function is not a constant expression
Here is a minimal working example
#include <fmt/format.h>
#include <string>
#include <string_view>
#include <source_location>
#include <concepts>
#include <cassert>
class DebugQueue
{
public:
bool addToTaskQueue(
std::string& strMessage,
std::string& strCategeory,
const std::source_location loc
)
{
return false;
};
bool addToISRQueue(
const std::string_view strFormatedDebugMessage,
const std::string_view strCategory,
const std::source_location loc)
{
return false;
};
};
class Log
{
public:
template <typename... Args>
bool logAsync(
fmt::format_string<Args...> fmt,
const std::string_view strCategory,
Args&&... args
);
template <typename String_T>
bool logAsync(
String_T& strFormatedDebugMessage,
String_T& strCategory,
const std::source_location loc = std::source_location::current()
);
static bool inHandlerMode();
private:
DebugQueue m_queue;
};
bool Log::inHandlerMode()
{
return false;
}
template<typename ...Args>
bool Log::logAsync(
fmt::format_string<Args...> fmt,
const std::string_view strCategory,
Args&&... args)
{
//if called from ISR we cannot call formatting functions since they will implicitly call new
bool bRes = false;
if (inHandlerMode())
{
fmt::basic_string_view<char> asStringView = fmt;
bRes = logAsync(std::string_view(asStringView.data()), strCategory);
}
else
{
std::string strFormatedMessage = fmt::format(fmt, std::forward<Args>(args)...);
std::string strCat(strCategory);
bRes = logAsync(strFormatedMessage, strCat);
}
}
template<typename String_T>
bool Log::logAsync(
String_T& strFormatedDebugMessage,
String_T& strCategory,
const std::source_location loc)
{
bool bRes = false;
if (inHandlerMode())
{
//called from ISR, do not use any dynamic memory allocation
//just add the unformated message to the queue
bRes = m_queue.addToISRQueue(strFormatedDebugMessage, strCategory, loc);
}
else
{
//called from Task Context
std::string strMsg;
std::string strCat;
if constexpr (std::same_as<std::string, String_T>)
{
std::swap(strMsg, strFormatedDebugMessage);
std::swap(strCategory, strCat);
}
else
{
strMsg = std::string(strFormatedDebugMessage.data());
strCategory = std::string(strCat.data());
}
bRes = m_queue.addToTaskQueue(strFormatedDebugMessage, strCategory, loc);
}
}
static Log g_log;
int main() {
fmt::print("The answer is {}.", 42);
g_log.logAsync("Info {}", "fooCat",1);
g_log.logAsync("Info", "fooCat");
}
https://godbolt.org/z/d7jeTjT6f
thx for your help guys :)
|
as suggested by @user17732522 in the comments the answer is
changing String_T& to String_T and renaming
template <typename String_T>
bool logAsync(
String_T& strFormatedDebugMessage,
String_T& strCategory,
const std::source_location loc = std::source_location::current()
);
to
template <typename String_T>
bool _logAsync(
String_T& strFormatedDebugMessage,
String_T& strCategory,
const std::source_location loc = std::source_location::current()
);
did solve my problem. Thx guys for your help:)
|
74,478,276
| 74,478,374
|
Constructor of virtual genetic class
|
I have this code:
sensor.h:
template<class T>
class Sensor {
public:
uint8_t address;
T data;
virtual void collectData() = 0;
Sensor(uint8_t address);
};
class TemperatureSensor: public Sensor<float> {
void collectData();
};
sensor.cpp:
template<typename T>
Sensor<T>::Sensor(uint8_t address) {
this->address = address;
}
void TemperatureSensor::collectData() {
//some code for collecitng data
}
main function:
TemperatureSensor sensor;
Serial.printf("%d", sensor.address);
Error:
src\sensor.cpp: In function 'void test()':
src\sensor.cpp:11:23: error: use of deleted function 'TemperatureSensor::TemperatureSensor()'
11 | TemperatureSensor sensor;
| ^~~~~~
In file included from src\sensor.cpp:1:
src/sensor.h:14:7: note: 'TemperatureSensor::TemperatureSensor()' is implicitly deleted because the default definition would be ill-formed:
14 | class TemperatureSensor: public Sensor<float> {
| ^~~~~~~~~~~~~~~~~
src/sensor.h:14:7: error: no matching function for call to 'Sensor<float>::Sensor()'
src/sensor.h:11:9: note: candidate: 'Sensor<T>::Sensor(uint8_t) [with T = float; uint8_t = unsigned char]'
11 | Sensor(uint8_t address);
| ^~~~~~
src/sensor.h:11:9: note: candidate expects 1 argument, 0 provided
src/sensor.h:6:7: note: candidate: 'constexpr Sensor<float>::Sensor(const Sensor<float>&)'
6 | class Sensor {
| ^~~~~~
src/sensor.h:6:7: note: candidate expects 1 argument, 0 provided
src/sensor.h:6:7: note: candidate: 'constexpr Sensor<float>::Sensor(Sensor<float>&&)'
src/sensor.h:6:7: note: candidate expects 1 argument, 0 provided
*** [.pio\build\nodemcuv2\src\sensor.cpp.o] Error 1
I want to have multiplte options of same base class(Sensor class) and extend it(I think this is rigth name). I cant create new instance of TemperatureSensor, from error i asume that i need to pass reference of Sensor, but I cant create new Sensor, beacuse it is virtual. Also this is not expected by me behavior. I want to create TemperatureSensor using constructor defined by Sensor ex: TemperatureSensor sensor(0xbeef/*address*/)
|
I want to create TemperatureSensor using constructor defined by Sensor ex: TemperatureSensor sensor(0xbeef/*address*/)
If you want to use base class constructor directly, you can use using
class TemperatureSensor: public Sensor<float> {
using Sensor::Sensor;
void collectData();
};
|
74,478,546
| 74,488,909
|
IOUserClientMethodArguments completion value is always NULL
|
I'm trying to use IOConnectCallAsyncStructMethod in order set a callback between a client and a driver in DriverKit for iPadOS.
This is how I call IOConnectCallAsyncStructMethod
ret = IOConnectCallAsyncStructMethod(connection, MessageType_RegisterAsyncCallback, masterPort, asyncRef, kIOAsyncCalloutCount, nullptr, 0, &outputAssignCallback, &outputSize);
Where asyncRef is:
asyncRef[kIOAsyncCalloutFuncIndex] = (io_user_reference_t)AsyncCallback;
asyncRef[kIOAsyncCalloutRefconIndex] = (io_user_reference_t)nullptr;
and AsyncCallback is:
static void AsyncCallback(void* refcon, IOReturn result, void** args, uint32_t numArgs)
{
const char* funcName = nullptr;
uint64_t* arrArgs = (uint64_t*)args;
ReadDataStruct* output = (ReadDataStruct*)(arrArgs + 1);
switch (arrArgs[0])
{
case 1:
{
funcName = "'Register Async Callback'";
} break;
case 2:
{
funcName = "'Async Request'";
} break;
default:
{
funcName = "UNKNOWN";
} break;
}
printf("Got callback of %s from dext with returned data ", funcName);
printf("with return code: 0x%08x.\n", result);
// Stop the run loop so our program can return to normal processing.
CFRunLoopStop(globalRunLoop);
}
But IOConnectCallAsyncStructMethod is always returning kIOReturnBadArgument and I can see that when the method:
kern_return_t MyDriverClient::ExternalMethod(uint64_t selector, IOUserClientMethodArguments* arguments, const IOUserClientMethodDispatch* dispatch, OSObject* target, void* reference) {
kern_return_t ret = kIOReturnSuccess;
if (selector < NumberOfExternalMethods)
{
dispatch = &externalMethodChecks[selector];
if (!target)
{
target = this;
}
}
return super::ExternalMethod(selector, arguments, dispatch, target, reference);
is called, in IOUserClientMethodArguments* arguments, completion is completion =(OSAction •) NULL
This is the IOUserClientMethodDispatch I use to check the values:
[ExternalMethodType_RegisterAsyncCallback] =
{
.function = (IOUserClientMethodFunction) &Mk1dDriverClient::StaticRegisterAsyncCallback,
.checkCompletionExists = true,
.checkScalarInputCount = 0,
.checkStructureInputSize = 0,
.checkScalarOutputCount = 0,
.checkStructureOutputSize = sizeof(ReadDataStruct),
},
Any idea what I'm doing wrong? Or any other ideas?
|
The likely cause for kIOReturnBadArgument:
The port argument in your method call looks suspicious:
IOConnectCallAsyncStructMethod(connection, MessageType_RegisterAsyncCallback, masterPort, …
------------------------------------------------------------------------------^^^^^^^^^^
If you're passing the IOKit main/master port (kIOMasterPortDefault) into here, that's wrong. The purpose of this argument is to provide a notification Mach port which will receive the async completion message. You'll want to create a port and schedule it on an appropriate dispatch queue or runloop. I typically use something like this:
// Save this somewhere for the entire time you might receive notification callbacks:
IONotificationPortRef notify_port = IONotificationPortCreate(kIOMasterPortDefault);
// Set the GCD dispatch queue on which we want callbacks called (can be main queue):
IONotificationPortSetDispatchQueue(notify_port, callback_dispatch_queue);
// This is what you pass to each async method call:
mach_port_t callback_port = IONotificationPortGetMachPort(notify_port);
And once you're done with the notification port, make sure to destroy it using IONotificationPortDestroy().
It looks like you might be using runloops. In that case, instead of calling IONotificationPortSetDispatchQueue, you can use the IONotificationPortGetRunLoopSource function to get the notification port's runloop source, which you can then schedule on the CFRunloop object you're using.
Some notes about async completion arguments:
You haven't posted your DriverKit side AsyncCompletion() call, and at any rate this isn't causing your immediate problem, but will probably blow up once you fix the async call itself:
If your async completion passes only 2 user arguments, you're using the wrong callback function signature on the app side. Instead of IOAsyncCallback you must use the IOAsyncCallback2 form.
Also, even if you are passing 3 or more arguments where the IOAsyncCallback form is correct, I believe this code technically triggers undefined behaviour due to aliasing rules:
uint64_t* arrArgs = (uint64_t*)args;
ReadDataStruct* output = (ReadDataStruct*)(arrArgs + 1);
switch (arrArgs[0])
The following would I think be correct:
ReadDataStruct* output = (ReadDataStruct*)(args + 1);
switch ((uintptr_t)args[0])
(Don't cast the array pointer itself, cast each void* element.)
Notes about async output struct arguments
I notice you have a struct output argument in your async method call, with a buffer that looks fairly small. If you're planning to update that with data on the DriverKit side after the initial ExternalMethod returns, you may be in for a surprise: an output struct arguments that is not passed as IOMemoryDescriptor will be copied to the app side immediately on method return, not when the async completion is triggered.
So how do you fix this? For very small data, pass it in the async completion arguments themselves. For arbitrarily sized byte buffers, the only way I know of is to ensure the output struct argument is passed via IOMemoryDescriptor, which can be persistently memory-mapped in a shared mapping between the driver and the app process. OK, how do you pass it as a memory descriptor? Basically, the output struct must be larger than 4096 bytes. Yes, this essentially means that if you have to make your buffer unnaturally large.
|
74,478,818
| 74,549,164
|
How to build a CMake project with MSVC 2015?
|
I try to build a CMake (v3.14) project with MSVC 2015. I use the CMake GUI to generate the makefile but when I hit the "Configure" button, I get the following error:
The C compiler identification is MSVC 19.0.24210.0
The CXX compiler identification is MSVC 19.0.24210.0
Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe
Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe -- broken
CMake Error at C:/Program Files/CMake/share/cmake-3.14/Modules/CMakeTestCCompiler.cmake:60 (message):
The C compiler
"C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe"
is not able to compile a simple test program.
It fails with the following output:
Change Dir: C:/Projets/geolibextern/build_msvc/CMakeFiles/CMakeTmp
Run Build Command(s):nmake /nologo cmTC_fa317\fast
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\nmake.exe" -f CMakeFiles\cmTC_fa317.dir\build.make /nologo -L CMakeFiles\cmTC_fa317.dir\build
Building C object CMakeFiles/cmTC_fa317.dir/testCCompiler.c.obj
C:\PROGRA~2\MICROS~2.0\VC\bin\amd64\cl.exe @C:\Users\egrace\AppData\Local\Temp\nm88C7.tmp
testCCompiler.c
Linking C executable cmTC_fa317.exe
"C:\Program Files\CMake\bin\cmake.exe" -E vs_link_exe --intdir=CMakeFiles\cmTC_fa317.dir --rc=rc --mt=CMAKE_MT-NOTFOUND --manifests -- C:\PROGRA~2\MICROS~2.0\VC\bin\amd64\link.exe /nologo @CMakeFiles\cmTC_fa317.dir\objects1.rsp @C:\Users\egrace\AppData\Local\Temp\nm8993.tmp
RC Pass 1: command "rc /foCMakeFiles\cmTC_fa317.dir/manifest.res CMakeFiles\cmTC_fa317.dir/manifest.rc" failed (exit code 0) with the following output:
Le fichier sp‚cifi‚ est introuvableNMAKE : fatal error U1077: '"C:\Program Files\CMake\bin\cmake.exe"' : return code '0xffffffff'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\nmake.exe"' : return code '0x2'
Stop.
I also tried (unsuccessfully) to reinstall the Visual C++ build tools or to use a more recent version of CMake.
|
Indeed, CMake couldn't find the program mt.exe because the Windows SDK folder wasn't in the PATH variable. To solve this problem, I need to execute this command with these arguments:
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64 8.1
|
74,479,052
| 74,531,214
|
Does NPP support overlapping streams?
|
I'm trying to perform multiple async 2D convolutions on a single image with multiple filters using NVIDIA's NPP library method nppiFilterBorder_32f_C1R_Ctx. However, even after creating multiple streams and assigning them to NPPI's method, the overlapping isn't happening; NVIDIA's nvvp informs the same:
That said, I'm confused if NPP supports overlapping context operations.
Below is a simplification of my code, only showing the async method calls and related variables:
std::vector<NppStreamContext> streams(n_filters);
for(size_t stream_idx=0; stream_idx<n_filters; stream_idx++)
{
cudaStreamCreateWithFlags(&(streams[stream_idx].hStream), cudaStreamNonBlocking);
streams[stream_idx].nStreamFlags = cudaStreamNonBlocking;
// fill up NppStreamContext remaining fields
// malloc image and filter pointers
}
for(size_t stream_idx=0; stream_idx<n_filters; stream_idx++)
{
cudaMemcpyAsync(..., streams[stream_idx].hStream);
nppiFilterBorder_32f_C1R_Ctx(..., streams[stream_idx]);
cudaMemcpy2DAsync(..., streams[stream_idx].hStream);
}
for(size_t stream_idx=0; stream_idx<n_filters; stream_idx++)
{
cudaStreamSynchronize(streams[stream_idx].hStream);
cudaStreamDestroy(streams[stream_idx].hStream);
}
Note: All the device pointers of the output images and input filters are stored in a std::vector, where I access them via the current stream index (e.g., float *ptr_filter_d = filters[stream_idx])
|
To summarize and add to the comments:
The profile does show small overlaps, so the answer to the title question is clearly yes.
The reason for the overlap being so small is just that each NPP kernel already needs all resources of the used GPU for most of its runtime. At the end of each kernel one can probably see the tail effect (i.e. the number of blocks is not a multiple of the number of blocks that can reside in SMs at each moment in time), so blocks from the next kernel are getting scheduled and there is some overlap.
It can sometimes be useful (i.e. an optimization) to force overlap between a big kernel which was started first and uses the full device and a later small kernel that only needs a few resources. In that case one can use stream priorities via cudaStreamCreateWithPriority to hint the scheduler to schedule blocks from the second kernel before blocks from the first kernel. An example of this can be found in this multi-GPU example (permalink).
In this case however, as the size of the kernels is the same and there is no reason to prioritize any of them over the others, forcing an overlap like this would not decrease the total runtime because the compute resources are limited. In the profiler view the kernels might then show more overlap but also each one would take more time. That is the reason why the scheduler does not overlap the kernels even though you allow it to do so by using multiple streams (See asynchronous vs. parallel).
To still increase performance, one could write a custom CUDA kernel that does all the filters in one kernel launch. The main reason that this could be a better than using NPP in this case is that all NPP kernels take the same input image. Therefore a single kernel could significantly decrease the number of accesses to global memory by reading in each tile of the input image only once (to shared memory, although L1 caching might suffice), then apply all the filters sequentially or in parallel (by splitting the thread block up into smaller units) and write out the results.
|
74,480,024
| 74,510,227
|
Is there a non-hacky way in libfmt to construct names for named arguments at runtime?
|
I am using libfmt to build a code generator that generates a sort of adapter layer around an existing library. So I have a dataset of parameter descriptions that include format strings describing the conversion from the data type in the outer layer to the data type in the inner layer. In the most simple case, this might look like
"{type_out} {var_out} = {var_in};\n"
in a more complex case, the conversion might depend on another parameter:
"int {var_out} = function_call({var_in}, {dependent_param__var_out});\n"
The name dependent_param (and as such any name that refers to one of its attributes, such as dependent_param__var_out) is not known to the code generator at compile time; it's constructed at runtime from the parameter dataset.
This means that I need to build a fmt::dynamic_format_arg_store some of whose named arguments are constructed at runtime. In essence, what I would like is along the lines of
#include <fmt/args.h>
#include <fmt/format.h>
#include <string>
fmt::dynamic_format_arg_store<fmt::format_context>
construct_arg_store(std::string const ¶mname) {
fmt::dynamic_format_arg_store<fmt::format_context> fmt_args;
// so far, so good.
fmt_args.push_back(fmt::arg("var_in", paramname));
fmt_args.push_back(fmt::arg("var_out", paramname + "_out"));
// imagine this were constructed by iterating over runtime-available data.
std::string argname = "dependent_param__var_out";
std::string argvalue = "dependent_param_out";
// Does not compile; fmt::arg expects char const *
fmt_args.push_back(fmt::arg(argname, argvalue));
return fmt_args;
}
int main() {
std::string fmtstring = "int {var_out} = function_call({var_in}, {dependent_param__var_out});\n";
auto args = construct_arg_store("foo");
fmt::vprint(fmtstring, args);
}
Right now, I build a symbol table from the dataset that contains std::string objects for all possible format arg names and use their .c_str() to build the fmt::arg objects (so that the generated C strings have a long enough lifetime). This works, but it seems like a bit of a dirty hack.
So I'm wondering, is there a better way to do it than that?
|
In general, it's better to use a template system like Mustache for this. That said, storing argument names as std::strings on the side and use them to construct dynamic_format_arg_store is OK. There is nothing hacky about it.
|
74,480,056
| 74,480,302
|
`operator type&` confusion
|
I have user-defined type:
class String::CharProxy
{
public:
const char* operator&() const;
char* operator&();
operator char() const;
operator char&();
};
The problem is when I'm trying to perform some explicit casts, the wrong operator is called:
CharProxy p(...);
static_cast<char>(p); // operator char&() call instead of operator char() const
I want operator char() const to be called when casting to char and operator char&() - when casting to char& only.
Could anyone explain how this mechanism works? Am I mistaken anywhere?
|
In your static_cast, both operator char() const and operator char&() are candidate functions as per [over.match.conv] because both char and char& are convertible to char via a standard conversion sequence.
Between the two functions, the compiler then decides by standard overload resolution rules. In these, operator char&() is found to be a better fit because its implicit this parameter has the same cv-qualifiers as the object you're passing into it (that is: there is no const qualifier on p). You can explicitly call the other operator with
static_cast<char>(static_cast<CharProxy const &>(p));
But in more realistic terms: 1. user-defined conversion functions are a hornets' nest that are best avoided 99% of the time, and 2. if your operator char() const has so different semantics from your operator char&() that you cannot use the latter where you can use the former, that seems like a very dangerous thing you're building there. Certainly it's not POLA-compliant.
|
74,480,093
| 74,480,877
|
pybind11: pass *C-style* function pointer as a parameter
|
I'm currently porting a C library to python using pybind11, and it has lots of C-style function pointers (i.e. not std::function, as described in https://pybind11.readthedocs.io/en/stable/advanced/cast/functional.html)
So my question is: is there an easy way to handle C style function pointers, when they are passed a function parameters?
For example I need to bind this function type (as an illustration, I took function pointers from the C library glfw)
typedef void (* GLFWmonitorfun)(GLFWmonitor* monitor, int event);
which is used like this:
void glfwSetMonitorCallback(GLFWmonitorfun cbfun)
I know I could wrap the function pointers in std::function, but it is quite cumbersome, since there are about 30 different function pointer types in the library, and I would need to patch manually all their usages.
Is there an easier way ?
PS: Below is how I could wrap them with std::function. Beware, this is borderline atrocious, since it requires global variable and global callbacks. This is exactly what I would like to avoid.
// C function pointer type
typedef void (* GLFWmonitorfun)(GLFWmonitor* monitor, int event);
// Wrapper std::function type
using GLFWmonitorfun_std = std::function<void(GLFWmonitor*, int)>;
// We need to store a global std::function pointer
GLFWmonitorfun_std globalGLFWmonitorfun_std;
// As well as a global C callback
void myGlobalCallback(GLFWmonitor* monitor, int event)
{
if (globalGLFWmonitorfun_std)
globalGLFWmonitorfun_std(monitor, event);
}
void py_init_module_glfw(py::module& m)
{
m.def("glfwSetMonitorCallback", [](const GLFWmonitorfun_std& f) {
// And we set the global std::function pointer in the binding
globalGLFWmonitorfun_std = f;
// Before setting the C callback
glfwSetMonitorCallback(myGlobalCallback);
});
// ....
|
Well, you need to store the function state somewhere. The simplest solution would be to put it in a local static variable:
m.def("glfwSetMonitorCallback", [](std::function<std::remove_pointer_t<GLFWmonitorfun>> f) {
static std::function<std::remove_pointer_t<GLFWmonitorfun>> callback;
callback = std::move(f);
glfwSetMonitorCallback([](GLFWmonitor* monitor, int event) {
callback(monitor, event);
});
});
|
74,480,645
| 74,482,353
|
Forward a variadic instance method call via a pointer to member function in C++
|
I'm working on a class representation utility that would work in a similar way to Java's Class class. That is, a mechanism that would emulate class reflection.
#include <map>
#include <stdexcept>
#include <string>
template<typename Class>
struct class_repr {
std::map<std::string, uintptr_t> fields;
std::map<std::string, void* (Class::*)(...)> methods;
void declare_field(const std::string& name, void* pointer) {
fields[name] = reinterpret_cast<uintptr_t>(pointer);
}
template<typename R, typename ...Params>
void declare_instance_method(const std::string& name, R (Class::* pointer)(Params...)) {
methods[name] = (void* (Class::*)(...)) pointer;
}
template<typename Tp>
Tp& get_field(void* object, const std::string& name) {
if (fields.count(name) == 0) throw std::invalid_argument("Field " + name + " not declared in the class descriptor");
return *reinterpret_cast<Tp*>(uintptr_t(object) + fields.at(name));
}
template<typename R, typename ...Params>
requires std::is_same_v<R, void>
void invoke_instance_method(void* object, const std::string& name, Params&& ... params) {
if (methods.count(name) == 0) throw std::invalid_argument("Method " + name + " not declared in the class descriptor");
(reinterpret_cast<Class*>(object)->*methods.at(name))(std::forward<Params>(params)...);
}
template<typename R, typename ...Params>
requires (not std::is_same_v<R, void>)
R invoke_instance_method(void* object, const std::string& name, Params&& ... params) {
if (methods.count(name) == 0) throw std::invalid_argument("Method " + name + " not declared in the class descriptor");
return *static_cast<R*>((reinterpret_cast<Class*>(object)->*methods.at(name))(std::forward<Params>(params)...));
}
};
And below is the class I'm testing it with:
#include <iostream>
class cat {
std::string name, color;
[[nodiscard]] const std::string& get_name() {
return name;
}
[[nodiscard]] const std::string& get_color() {
return color;
}
void say(std::string&& what) {
std::cout << "[" << name << "]: " << what << std::endl;
}
void meow() {
say("meow");
}
void say_color() {
say("my fur is " + color);
}
public:
cat(std::string name, std::string color) : name(std::move(name)), color(std::move(color)) {}
static class_repr<cat> get_representation() {
class_repr<cat> descriptor;
descriptor.declare_field("name", &(static_cast<cat*>(nullptr)->name));
descriptor.declare_field("color", &(static_cast<cat*>(nullptr)->color));
descriptor.declare_instance_method("get_name", &cat::get_name);
descriptor.declare_instance_method("get_color", &cat::get_color);
descriptor.declare_instance_method("say", &cat::say);
descriptor.declare_instance_method("meow", &cat::meow);
descriptor.declare_instance_method("say_color", &cat::say_color);
return descriptor;
}
};
This code works fine:
int main() {
cat kitty("marble", "white");
class_repr cat_class = cat::get_representation();
cat_class.get_field<std::string>(&kitty, "name") = "skittle";
cat_class.get_field<std::string>(&kitty, "color") = "gray";
cat_class.invoke_instance_method<void>(&kitty, "meow");
cat_class.invoke_instance_method<void>(&kitty, "say_color");
std::cout << cat_class.invoke_instance_method<std::string>(&kitty, "get_name") << "'s color is indeed "
<< cat_class.invoke_instance_method<std::string>(&kitty, "get_color") << std::endl;
return 0;
}
But when I try to call the say function, the code doesn't compile because non-primitive type objects cannot be passed through variadic method:
cat_class.invoke_instance_method<void, std::string&&>(&kitty, "say", "purr"); // error
Is there any way around making this work as intended (so that it calls an equivalent of kitty.say("purr"))?
|
You can create a class representing any member function using type erasure (modified from this SO answer). No void*, no C-stype ellipsis ....
#include <memory>
#include <any>
#include <vector>
#include <functional>
class MemberFunction
{
public:
template <typename R, typename C, typename... Args>
MemberFunction(R (C::* memfunptr)(Args...))
: type_erased_function{
std::make_shared<Function<R, C, Args...>>(memfunptr)
}
{}
template <typename R, typename C, typename... Args>
R invoke(C* obj, Args&&... args){
auto ret = type_erased_function->invoke(
std::any(obj),
std::vector<std::any>({std::forward<Args>(args)...})
);
if constexpr (!std::is_void_v<R>){
return std::any_cast<R>(ret);
}
}
private:
struct Concept {
virtual ~Concept(){}
virtual std::any invoke(std::any obj, std::vector<std::any> const& args) = 0;
};
template <typename R, typename C, typename... Args>
class Function : public Concept
{
public:
Function(R (C::* memfunptr)(Args...)) : func{memfunptr} {}
std::any invoke(std::any obj, std::vector<std::any> const& args) override final
{
return invoke_impl(
obj,
args,
std::make_index_sequence<sizeof...(Args)>()
);
}
private:
template <size_t I>
using Arg = std::tuple_element_t<I, std::tuple<Args...>>;
template <size_t... I>
std::any invoke_impl(std::any obj, std::vector<std::any> const& args, std::index_sequence<I...>)
{
auto invoke = [&]{
return std::invoke(func, std::any_cast<C*>(obj), std::any_cast<std::remove_reference_t<Arg<I>>>(args[I])...);
};
if constexpr (std::is_void_v<R>){
invoke();
return std::any();
}
else {
return invoke();
}
}
R (C::* func)(Args...);
};
std::shared_ptr<Concept> type_erased_function;
};
You store a std::map<std::string, MemberFunction> in your class_repr and change your declare_instance_method and invoke_instance_method like so:
template<typename R, typename ...Params>
void declare_instance_method(const std::string& name, R (Class::* pointer)(Params...)) {
methods.insert({name, MemberFunction(pointer)});
}
template<typename R, typename ...Params>
requires std::is_same_v<R, void>
void invoke_instance_method(Class* object, const std::string& name, Params&& ... params) {
if (methods.count(name) == 0) throw std::invalid_argument("Method " + name + " not declared in the class descriptor");
methods.at(name).invoke<void>(object, std::forward<Params>(params)...);
}
template<typename R, typename ...Params>
requires (not std::is_same_v<R, void>)
R invoke_instance_method(Class* object, const std::string& name, Params&& ... params) {
if (methods.count(name) == 0) throw std::invalid_argument("Method " + name + " not declared in the class descriptor");
return methods.at(name).invoke<R>(object, std::forward<Params>(params)...);
}
Live Demo
Note that this is a prototype. To make this generally applicable you still need to invest quite a bit of work: You have to consider const member functions and const arguments, member functions mutating inputs or returning references etc. Also note, that std::any stores by value, so you might create some unnecessary copies of the function arguments.
|
74,481,147
| 74,481,311
|
How to clear cin input buffer
|
int main() {
string inputName;
int age;
// Set exception mask for cin stream
cin.exceptions(ios::failbit);
cin >> inputName;
while (inputName != "-1") {
// FIXME: The following line will throw an ios_base::failure.
// Insert a try/catch statement to catch the exception.
// Clear cin's failbit to put cin in a useable state.
try
{
cin >> age;
cout << inputName << " " << (age + 1) << endl;
}
catch (ios_base::failure& excpt)
{
age = 0;
cout << inputName << " " << age << endl;
cin.clear(80, '\n');
}
inputName = "";
cin >> inputName;
}
return 0;
}
I'm unable to clear cin after catching the exception, even trying to set the variable to an empty string... my program stops at cin >> inputName; after the exception is caught but I thought cin.clear(80, '\n'); resets cin and puts it in a usable state?
Debugger is telling me that there is an unhandled exception when I try to input another string into inputName variable. Any help is appreciated, thank you.
|
I don't quite understand what you want to fix. In any case, I just fixed the problem with cleaning the cin.
#include <iostream>
#include <limits>
using namespace std;
int main() {
string inputName;
int age;
// Set exception mask for cin stream
cin.exceptions(ios::failbit);
cout << "Input name: ";
cin >> inputName;
while (inputName != "-1") {
// FIXME: The following line will throw an ios_base::failure.
// Insert a try/catch statement to catch the exception.
// Clear cin's failbit to put cin in a useable state.
try {
cout << "Age: ";
cin >> age;
cout << inputName << " " << (age + 1) << endl;
break;
}
catch (ios_base::failure& except) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
return 0;
}
As you can see, I don't pass any parameters to cin.clear() as this method simply resets the state flags inside the cin. To empty the cin buffer instead you have to use cin.ignore() passing two parameters, the first is the size of the buffer, in this case, I used numeric_limits to specify it, while the second parameter is to tell it what the end character is.
|
74,481,793
| 74,482,021
|
Use std::string_view size in template parameter from NTTP constructor
|
I have a simple C++20 compile-time string type that is defined like this:
template<std::size_t N>
class compile_time_string_storage
{
public:
constexpr compile_time_string_storage(std::array<char, N> str) noexcept
: value(str)
{
}
constexpr compile_time_string_storage(const char (&str)[N]) noexcept
{
std::copy_n(str, N, value.begin());
}
constexpr compile_time_string_storage(char c) noexcept
: value{ c }
{
}
std::array<char, N> value;
};
compile_time_string_storage(char)->compile_time_string_storage<1>;
template<compile_time_string_storage S>
class str
{
public:
[[nodiscard]] constexpr static std::string_view get() noexcept
{
return { S.value.data(), size_ };
}
[[nodiscard]] constexpr static std::size_t size() noexcept { return size_; }
private:
constexpr static std::size_t calculate_size() noexcept
{
auto count = std::size_t{ 0 };
for (; count < S.value.size(); ++count) {
if (S.value[count] == '\0') {
break;
}
}
return count;
}
constexpr static std::size_t size_ = calculate_size();
};
This works. However I would like to add support of construction via std::string_view, which in principle should be straightforward as it can be constexpr-constructed, but I'm struggling.
Initially I added a constexpr constructor overload to compile_time_string_storage with a deduction guide:
<source>:55:80: error: non-type template argument is not a constant expression
compile_time_string_storage(std::string_view str)->compile_time_string_storage<str.size()>;
^~~~~~~~~~
The constructor argument can't be used in a compile-time context. I then tried using the deduction guide as 'tag' I can specialise on:
constexpr auto string_view_tag = std::numeric_limits<std::size_t>::max();
template<>
class compile_time_string_storage<string_view_tag>
{
public:
constexpr compile_time_string_storage(std::string_view str) : value(str)
{}
std::string_view value;
};
compile_time_string_storage(std::string_view)->compile_time_string_storage<string_view_tag>;
Nope, can't use that:
<source>:52:22: note: 'compile_time_string_storage<string_view_tag>' is not a structural type because it has a non-static data member of non-structural type 'std::string_view' (aka 'basic_string_view<char>')
std::string_view value;
^
/opt/compiler-explorer/gcc-11.2.0/lib/gcc/x86_64-linux-gnu/11.2.0/../../../../include/c++/11.2.0/string_view:510:18: note: 'std::string_view' (aka 'basic_string_view<char>') is not a structural type because it has a non-static data member that is not public
size_t _M_len;
^
OK, what if I make an equivalent 'structural' version of std::string_view?
struct str_view
{
constexpr str_view(std::string_view str) : data_{str.data()}, size_{str.size()}
{}
constexpr const char* const data() const noexcept { return data_; }
constexpr std::size_t size() const noexcept { return size_; }
const char* data_;
std::size_t size_;
};
template<>
class compile_time_string_storage<string_view_tag>
{
public:
constexpr compile_time_string_storage(std::string_view str) : value(str)
{}
str_view value;
};
Nope.
<source>:88:23: error: pointer to subobject of string literal is not allowed in a template argument
static_assert(str<"hello"sv>::get() == "hello");
^
Is there a way of using a std::string_view to initialise compile_time_string_storage?
I'm currently using the deduction guide to set a fixed value for N (set by a compiler define), which works in the sense that the compiler is smart enough to just keep the original string data in static storage rather than the std::array contents. But it's hack as you need to know the maximum string length you'll need up front, and it's just not right.
|
Is there a way of using a std::string_view to initialise compile_time_string_storage?
Your problem is that you seem to want a number of things that cannot all go together. You want:
To create a compile_time_string_storage from a constexpr string_view without specifying the size explicitly as a template parameter.
To have the compile_time_string_storage provide an array of N characters of storage for the string.
You cannot have both. So long as compile_time_string_storage has a size template parameter that must be filled in by a property of a non-template parameter, this will not work. Function parameters, and therefore members of them, are not constexpr.
Your last attempt drops #2, and that approach can work. However, you ran into a separate problem: pointers to string literals cannot be used as template parameters. You cannot smuggle them into template parameters as members of some other object either.
It would have worked if you used a stack array of strings as your source for the string_view. Of course, then your "compile_time_string_storage` would be a lie, because it would not actually store the string. It would be referencing existing storage that may or may not exist by the time someone uses the string.
If your ultimate goal requires the ability to shove a string literal pointer into this class without copying characters, give it up. The standard expressly forbids it. So you're left with having the string store an array.
An array whose size cannot come from a function parameter.
So your only recourse is to do it manually: take the constexpr string_view, get its size, and pass that size explicitly as a template parameter:
constexpr compile_time_string_storage<some_constexpr_string_view.size()> var(some_constexpr_string_view);
It's ugly, but that's your only option.
Alternatively, avoid string_view altogether and use a span<char const, N> constructed from a string literal. span is able to maintain the size of the span as a template parameter, which in turn allows your compile_time_string_storage to extract it without having to manually insert the template argument.
|
74,482,149
| 74,482,588
|
Making linker errors more helpful through specificity (C/C++)
|
This is my first time asking a question here, as I'm usually able to find answers in previous posts, but I can't find any information on this topic.
I'm trying to write C/C++ header files that can be reused between projects. One of my headers uses <math.h> (deprecated in C++, so it uses <cmath> instead). When I compile a C++ program to test the header, it works perfectly. When I compile a C program to test the header, the linker rightfully throws a fit unless "libm.a" is linked ("-l m" in most compilers). I'm not worried about myself forgetting to link the library, but I plan on making these headers available for public use, and I'd like to print a more helpful error message than "undefined reference". Here's my question, is there any way for me to use something akin to preprocessor directives to check if a specific library is linked properly when building the executable so I can throw my own error message?
Source code: https://github.com/LimikEcho/rlx/blob/main/itosa.h
I've tried checking if specific macros are defined (from both <math.h> and <math.c>). If I check a macro defined in <math.h>, it returns 1 regardless of linking "libm.a". If I check a macro defined in <math.h>, it returns 0 regardless of linking "libm.a". I understand why that is, but it was worth a shot.
Edit: People seem to be missing the point of this, so let me reiterate. I want to know if it's possible to influence the error handling of the linker from a header, that way whenever it's used by third parties, they can be accurately warned about missing a specific library. I want to display undefined reference errors as something like undefined reference to 'example_function', did you forget to link 'libm.a'?
|
The build process runs in different phases. The compilation phase takes your program code including the header file and produces a so called object files (with the file extension .o).
The same applies for your library. You get a set of object files. When you tell the compiler to produce a static library it takes a set of object files and put them all together into a static library (with the file extension .a).
When everything is compiled the linking phase is started. In that phase the object files and the static library is combined into one executable file.
That means, there is no way to check at the compilation phase the existence of the static library file. Because that file comes into game at the linking phase. The compilation needs only the header file. And this was not your question.
If a mechanism for loading libraries is needed, you must use a build tool like make. These give you the comfort you are asking for. But such tools normally don't have the purpose to integrate foreign static libraries, although this should be possible.
But what you try to achieve is also not advisable. It is not guaranteed that it will work if you and who uses the static library uses different versions of the compiler or different compiler options. The code of a static library is directly integrated into a binary. The linker integrates it for you. This requires 100% compatibility between both compilers. As far as I know, there is no mechanism that protects you from incompatibilities. Your use case is relatively exotic. It is no simple question to tell you what could go wrong with it (see also this not answered question: Static link library compatibility with newer compiler versions).
If you don't want to deliver the source code of your library, then you should consider shared libraries. Shared libraries are exactly made for the purpose you are asking for. You link them at runtime. The operating system does it. And you can also check at runtime if they exist or not.
On Windows shared libraries have the file extension .dll. On Linux they have the file extension .so.
For more information see Difference between static and shared libraries? and How do I find out what all symbols are exported from a shared object?.
Partial Solution
The following solution could give you at least some sort of indication when forgetting to link against a.
Your library header a.h is this:
void please_link_a();
void your_library_function();
Your library code a.c is this:
void please_link_a(){
return;
}
void your_library_function() {
return;
}
But then you don't give a.h to the users of your library. Instead you modify it by adding something that triggers a linker warning against please_link_a. So you give a file alib.h with the following contents.
void please_link_a();
void check_if_a_linked(){
please_link_a();
}
What the user now forgets to link the static library, he sees all the linker errors for his code, but in addition this error:
/usr/bin/ld: /tmp/cczi8mca.o: in function `check_if_a_linked':
main.c:(.text+0xa): undefined reference to `please_link_a'
If it is not your own library, you cannot achieve the please_link_a part of the message. But the check_if_a_linked part you can. Just call anything else from the library. You can always manually change the header file that you got from the author and add such a function. But I don't know if this is practical for you. The linker error is still not so nice.
|
74,483,053
| 74,486,126
|
Why does my vulkan compute shader receive a 0.0 float as -170146355474918162907645410264962039808.0?
|
I'm working on a small vulkan app that utilises compute shaders to transform some geometry data. This data is sent to a single compute shader via multiple storage buffers.
To ensure that everything is reaching my compute shader as expected (no byte alignment issues etc.), i've temporarily created an output buffer to which I simply copy input data on GPU side and print it to console from CPU side.
The data in question is a buffer of instance structs:
struct instance
{
alignas(8) glm::vec2 position;
alignas(8) glm::uvec2 colours;
alignas(4) uint32_t object_index;
alignas(4) float scale;
alignas(4) float rotation;
alignas(4) uint32_t FILLER = 0;
};
The shader (GLSL) receives the buffer the following way:
struct instance
{
vec2 position;
uvec2 colours;
uint object_index;
float scale;
float rotation;
uint FILLER;
};
I am creating two instances:
at 0, 0
at 1, 1
I am printing the contents of my output buffer the following way (the buffer has 256 slots, but for debug purposes i'm only printing the first 16):
float* output_buffer_pointer;
vkMapMemory( *get_hardware(), *get_buffer_memory(), offset, 256, 0, (void**) &output_buffer_pointer );
for (int i = 0; i < 16; i++)
{
cout << i << ": " << output_buffer_pointer[i] << endl;
}
cout << endl;
vkUnmapMemory( *get_hardware(), *get_buffer_memory() );
Sending a buffer of a couple of instances to the compute shader and simply copying the position x and y to my debug output buffer (into separate slots) results in mostly expected numbers, EXCEPT the x coordinate of the first instance:
0: -170146355474918162907645410264962039808.00000000 (x of instance 1)
1: 0.00000000 (y of instance 1)
2: 1.00000000 (x of instance 2)
3: 1.00000000 (y of instance 2)
The expected result should be:
0: 0.00000000
1: 0.00000000
2: 1.00000000
3: 1.00000000
This is also the very first byte that should be in my allocated memory (the instance buffer is the first one at offset 0) - not sure if that information may be relevant.
It can't be a byte alignment issue, since all other data is correct.
I've tried changing the x coordinate of the first instance, but the output number didn't change as far as I could tell.
Other fields within the first instance (e.g. the "colours" field) return correct data.
|
As @chux-ReinstateMonica correctly pointed out, the hex code of above float is ff0000ff, which does look like a colour hex code imo.
Turns out I forgot to set the offset in the vkBindBufferMemory instruction, causing my colour buffer to overwrite my instances.
It was only by coincidence, that the y-coordinate of the first instance and the second colour appeared the same in float notation:
y coordinate 0.0 and blue (0000ffff) both appear as 0.0 in the console, since blue is an incredibly small number (9.18340948595268867429866182409 E-41).
|
74,483,127
| 74,491,504
|
how to get a GET/POST variable with a c++ CGI program?
|
my google-fu has failed me, I'm looking for a basic way to get GET/POST data from an html forum page on my server to use in a c++ CGI program using only basic libraries.
(using an apache server, on ubuntu 22.04.1)
here's the code I've tried
the HTML page:
<!doctype html>
<html>
<head>
<title>Our Funky HTML Page</title>
</head>
<body>
Content goes here yay.
<h2>Sign Up </h2>
<form action="cgi-bin/a.cgi" method="post">
<input type="text" name="username" value="SampleName">
<input type="password" name="Password" value="SampleName">
<button type="submit" name="Submit">Text</button>
</form>
</body>
</html>
and here's the c++ code I've tried:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Content-type:text/plain\n\n");
printf("hello World2\n");
// attempt to retrieve value of environment variable
char *value = getenv( "username" ); // Trying to get the username field
if ( value != 0 ) {
printf(value);
} else {
printf("Environment variable does not exist."); // if it failed I get this message
}
printf("\ncomplete\n");
return 0;
}
I get the feeling 'getenv' is not the right thing to use here.. it works for things like "SERVER_NAME" though.
any thoughts?
|
okay, 2 different methods, depending if it's a post or get method:
-GET-
html:
<!doctype html>
<html>
<head>
<title>Website title obv</title>
</head>
<body>
Content goes here yay.
<h2>Sign Up </h2>
<form action="cgi-bin/a.cgi" method="get">
<input type="text" name="username" value="SampleName">
<input type="password" name="Password" value="SampleName">
<button type="submit" name="Submit">Text</button>
</form>
</body>
</html>
and the c++ (script?) to read the get values:
#include <stdio.h>
#include <iostream>
int main()
{
printf("Content-type:text/plain\n\n");
char *value = getenv( "QUERY_STRING" ); // this line gets the data
if ( value != 0 ) {
printf(value);
} else {
printf("Environment variable does not exist.");
}
return 0;
}
you have to manually parse the data
-POST-
html:
just change 'get' to 'post'
c++:
#include <stdio.h>
#include <iostream>
#include <string>
#include <stdlib.h>
int main()
{
printf("Content-type:text/plain\n\n");
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
return 0;
}
again, you'll have to manually parse the data, but now you have those values to play around with yourself.
have fun!
|
74,483,386
| 74,483,405
|
Best datastructure for iterating over and moving elements to front
|
As part of a solution to a bigger problem that is finding the solution to a maximum flow problem. In my implementation of the relabel-to-front algorithm I'm having a performance bottleneck that I didn't expect.
The general structure for storing the graph data is as follows:
struct edge{
int destination;
int capacity;
};
struct vertex{
int e_flow;
int h;
vector<edge> edges;
};
The specifics of the algorithm are not that important to the question. In the main loop of the solution I'm looping over all vertices except the source and the sink. If at some point a change is made to a vertex then that vertex is put at the front of the list and the iteration starts again from the start. Until the end of the list is reached and we terminate. This part looks as follows now
//nodes are 0..nodeCount-1 with source=0 and sink=nodeCount-1
vector<int> toDischarge(nodeCount-2,0);
for(int i=1;i<sink;i++){
toDischarge[i-1]=i;
}//skip over source and sink
//custom pointer to the entry of toDischarge we are currently accessing
int point = 0;
while(point != nodeCount-2){
int val = toDischarge[point];
int oldHeight = graph[val].h;
discharge(val, graph, graph[val].e_flow);
if(graph[val].h != oldHeight){
rotate(toDischarge.begin(), toDischarge.begin()+point, toDischarge.begin()+point+1);
//if the value of the vertex has changed move it to the front and reset pointer
point = 0;
}
point++;
}
I tried using an std::list data structure before the vector solution but that was even slower even though conceptually that didn't make sense to me since (re)moving elements in a list should be easy. After some research I found out that it was probably horribly performant due to caching issues with list.
Even with the vector solution though I did some basic benchmarking using valgrind and have the following results.
If I understand this correctly then over 30% of my execution time is just spent doing vector element accesses.
Another solution I've tried is making a copy of the vertex needed for that iteration into a variable since it is accessed multiple times, but that was even worse performance because I think it is also making a copy of the whole edge list.
What data structure would improve the general performance of these operations? I'm also interested in other data structures for storing the graph data if that would help.
|
It seems to me that this is what std::deque<> is for. Imagine it as a 'non-continuous vector', or some vector-like batches tied together. You can use the same interface as vector, except that you cannot assume that adding an index to the first element's pointer results in the given element (or anything sensible other than UB); you need to use [] for indexing. Also, you have dq.insert(it, elem); that's quick if it is std::begin(it) or std::end(it).
|
74,483,471
| 74,483,834
|
How do I use test cases for competitive programming? CodeChef C++
|
I've just started getting into competitive programming on CodeChef and I was working on this challenge and for the most part, it works, but I'm not sure how to implement the test cases. I've seen solutions where people use a while loop and decrement the T, I tried that but I had no luck.
Here is the Problem statement:
Problem: If Give an integer N . Write a program to obtain the sum of the first and last digits of this number.
Input: The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains an integer N.
#include <iostream>
#include <string>
using namespace std;
// First and Last Digit
int main() {
// your code goes here
// 1. T for test cases
int T;
// 2. Get input from N;
int N;
cout<<"Enter number: ";
cin>>N;
// 3. Convert int to string
string convert = to_string(N);
// 4. Get index [0] and [string length - 1]
string first;
string last;
for(int i = 0; i < convert.length(); i++)
{
first = convert[0];
last = convert[convert.length() - 1];
}
// 5. convert single digit to int
int firstDigit = stoi(first);
int lastDigit = stoi(last);
// 6. add both numbers
int total = firstDigit + lastDigit;
// 7. output both numbers
cout<<total;
return 0;
}
|
Competitive programming is fun! It's a good exercise for writing compact and fast code.
Don't be thrown off by the term 'test cases', it's just a fancy name for 'numbers'. First read T, then read N, looping T times.
Something a bit like that:
size_t T;
std::cin >> T;
while (T--) // loop T times
{
std::string N; // read N as a string
std::cin >> N; // this will skip all whitespace and only
// give us the good stuff. \n is a whitespace.
// ...
auto sum = (N.front() - '0') + (N.back() - '0');
// ...
}
|
74,483,661
| 74,483,704
|
C++ convert an unsigned int in range [0, 2^n) to signed int in range [-2^(n-1), 2^(n-1) )
|
At the outset, I realize what I did was bad. I relied on what is now (at least) undefined behavior, if not explicitly forbidden. It used to work, and I thought I was being clever. Now it doesn't and I'm trying to fix it.
I have positive power-of-2 numbers (FFT bin index, but not important). I want to effectively FFT-shift a set of bin indices by wrapping the second half of the values to the negative range. That is, given an FFT size of 512,
0 ... 255 -> 0 ... 255
256 ... 511 -> -256 ... -1
What used to work was
template <size_t N>
struct Wrapper {
int val : N;
};
auto constexpr index = 42u;
auto wrapper = Wrapper<9>{ index }; // warning: invalid narrowing conversion from "unsigned int" to "int"
auto val = wrapper.val; // signed value
This relied on the truncation of overflowed assignment, but was empirically tested and Just Worked(tm).
Now, it doesn't compile (cleanly).
How should I perform this conversion now?
|
How about:
auto wrapper = Wrapper<9>{ index & (1 << (9 - 1)) ? long(index) - 2 * (1 << (9 - 1)) : index };
If, for some reason (e.g. performance), ternary is not preferred, then you might also try:
auto wrapper = Wrapper<9>{ long(index) - 2 * (index & (1 << (9 - 1))) };
|
74,484,422
| 74,484,453
|
how to use if else c++
|
How do you provide a condition in the if statement, if the variable is an integer data type then it will be displayed, and if the variable is any other data type then something else will be displayed?
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
using namespace std;
int main() {
char pilih,pilih2;
int p, l, a, t, r,ulang = 4;
float luas1, luas2, luas3, keliling1, keliling2, keliling3, phi = 3.14;
while (ulang > 0) {
pilihUlang:
cout << "Pilih jenis bangun datar berikut :\n 1. Persegi panjang\n 2. Segitiga sama sisi\n 3. Lingkaran" << endl;
cout << "Masukan pilihan anda [1/2/3] : ";
cin >> pilih;
system("cls");
switch (pilih) {
case '1':
system("color 07");
cout << "Luas Dan Keliling Persegi Panjang" << endl;
cout << "Masukan Panjang = ";
cin >> p;
if (?) { // <-- here
cout << "Masukan Lebar = ";
cin >> l;
system("cls");
cout << "Luas dan keliling Persegi Panjang dengan panjang " << p << " dan lebar " << l << ", yaitu :" << endl;
luas1 = p * l;
keliling1 = 2 * (p + l);
cout << "Luas = " << luas1 << endl;
cout << "Keliling = " << keliling1 << endl;
cout << "Sisa bisa memilih ulang " << ulang - 1 << " kali." << endl;
break;
}
else {
//...
}
|
From the istream::operator>> man page:
If extraction fails (e.g. if a letter was entered where a digit is
expected), zero is written to value and failbit is set.
So, your function could test the cin.good() method to see if the >> operation was successful, like this:
cin >> p;
if (cin.good()) {
cout << "The integer you typed was " << p << endl;
} else {
cout << "Hey, that wasn't an integer!" << endl;
}
|
74,485,364
| 74,485,609
|
What actually happens when this type of condition in the for loop is checked?
|
I can't understand the difference between the condition checked in a for loop and an if condition. Do both behave in a different way?
When I write:
int num = 10;
for(int i = 0; i < 15 && num; i++){
cout << i << " ";
}
It only checks whether i < 15 and it doesn't check for i < num and prints all the way from 0 to 14.
But at the same time, if I write a if condition like:
if(x < 15 && num)
It checks for both x < 15 and x < num.
|
The condition of a loop (whether a for loop, a while loop, or a do..while loop), and the condition of an if, are both boolean contexts and thus work in exactly the same way.
Both of your assertions are wrong, in that the compiler never checks for either i < num or x < num in your example, that is not how && works.
In for(int i = 0; i < 15 && num; i++), the condition is parsed as (i < 15) && (num != 0), which in your example is effectively (i < 15) && true, or simply (i < 15). If you want to check for (i < num) then you need to code it that way:
for(int i = 0; i < 15 && i < num; i++)
Alternatively:
for(int i = 0; i < min(15,num); i++)
In if(x < 15 && num), the condition is parsed as (x < 15) && (num != 0), which in your example is effectively (x < 15) && true, or simply (x < 15). If you want to check for (x < num) then you need to code it that way:
if(x < 15 && x < num)
Alternatively:
if(x < min(15,num))
|
74,485,536
| 74,485,588
|
std::function error conversion from ‘x' to non-scalar type ‘y’ requested?
|
I have the following code to demonstrate a function been called inside another function.
The below code works correctly:
#include <iostream>
#include <functional>
int thirds(int a)
{
return a + 1;
}
template <typename T, typename B , typename L>
//------------------------------------------------VVVVV-
int hello(T x, B y, L func)
{
int first = x + 1;
int second = y + 1;
int third = func(6);
return first + second + third;
}
int add()
{
std::function<int(int)> myfunc = thirds;
return hello(1, 1, myfunc); // pass thirds function from here
}
int main()
{
std::cout << add();
return 0;
}
Live Here
But Now I want to pass a function( thirds) of type Number ( A C++ class ) with return type std::vector<uint8_t>
thirds function
std::vector<uint8_t> thirds(Number &N)
{
std::vector<uint8_t> z;
z.push_back(N.z);
return z ;
}
Here is the full code ( Live here )and How I am doing it.
#include <stdio.h>
#include <iostream>
#include <functional>
class Number{
public:
int z = 5;
};
std::vector<uint8_t> thirds(Number &N)
{
std::vector<uint8_t> z;
z.push_back(N.z);
return z ;
}
template <typename T, typename B , typename L>
//------------------------------------------------VVVVV-
int hello(T x, B y, L func)
{
int first = x + 1;
int second = y + 1;
Number N;
std::vector<uint8_t> third = func(N);
return first + second ;
}
int add()
{
std::function<std::vector<uint8_t>(Number)> myfunc = &thirds;
return hello(1, 1, myfunc);
}
int main()
{
std::cout << add();
return 0;
}
I am getting a error:
error: conversion from ‘std::vector (*)(Number&)’ to non-scalar type ‘std::function(Number)>’ requested
std::function<std::vector<uint8_t>(Number)> myfunc = &thirds;
Can Someone please show me what I am doing wrong? How can I solve it?
|
std::vector<uint8_t> thirds(Number &N) : Argument type is Number&.
Therefore, you need '&' :
std::function<std::vector<uint8_t>(Number&)> myfunc = &thirds;
|
74,485,714
| 74,485,871
|
linked list not printing output
|
I have to dynamically allocate a list of robots for a school project. In an actual program, there will be other member functions that will require the list of names in order to perform certain functions.
As of right now, I just learned about this concept, and have tried really hard to put together some things I have seen online. The issue at the moment is that I can not tell if my list is properly being stored -- I am also getting wonky output when I try to call my display of list function.
Please help if you can. Also, I am happy to hear any tips for literally anything, as I am fairly new to programming.
class Node{
public:
std::string name_;
Node* next;
};
class linkedBotList{
public:
linkedBotList() {head = nullptr;} //constructor
~linkedBotList(){}; // destructure
void addNode();
void display();
private:
Node* head;
};
int main(int argc, const char * argv[]) {
linkedBotList* list = new linkedBotList();
int siz;
std::cout << "How many Robots?" << std::endl;
std::cout << "What are the names?" << std::endl;
std::cin >> siz;
for(int i = 0; i < siz; i++){
list->addNode();
}
delete list;
return 0;
}
void linkedBotList::addNode(){
std::string botName;
Node* newNode = new Node();
newNode->name_ = botName;
newNode->next = nullptr;
std::cin >> botName;
if(head == nullptr){
head = newNode;
}
else {
Node* temp = head; // head is not null
while(temp->next != nullptr){ // go until at the end of the list
temp = temp->next;
}
temp->next = new Node; // linking to new node
}
}
void linkedBotList::display() {
if (head == NULL) {
std::cout << "List is empty!" << std::endl;
}
else {
Node* temp = head;
while (temp != NULL) {
std::cout << "Made it to display funct.\n";
std::cout << temp->name_ << " ";
temp = temp->next;
}
std::cout << std::endl;
}
}
I did try a few things, like switching around my temp variable, and a few other re-assignments. Maybe someone can quickly spot the issue and help?
|
Your display function is fine.
The problem is that you have 2 logic flaws in addNode():
you are not storing strings in your list correctly. You are assigning botName to newNode->name_ before botName has been assigned a value. So all of your nodes have empty strings. Assigning botName afterwards will not update newNode->name_. 1
if the list is not empty, you iterate to the end of the list correctly 2, but then you assign a new blank node to temp->next instead of assigning your newNode that you already populated. And your Node constructor is not initializing the next member to nullptr, so you are creating a corrupted list, which will cause subsequent loops through the list to invoke undefined behavior.
Try this instead:
void linkedBotList::addNode(){
std::string botName;
std::cin >> botName; // <-- move up here
Node* newNode = new Node{botName, nullptr};
if (!head){
head = newNode;
}
else {
Node* temp = head;
while (temp->next){
temp = temp->next;
}
temp->next = newNode; // <-- linking to new node
}
}
Alternatively, you can eliminate the if like this:
void linkedBotList::addNode(){
std::string botName;
std::cin >> botName;
Node** temp = &head;
while (*temp){
temp = &((*temp)->next);
}
*temp = new Node{botName, nullptr};
}
1: A better design would be to have addNode() take in a string as an input parameter, and then move the cin call into your loop in main().
2: consider adding a tail member to your list to avoid having to loop on each addition.
Try this alternate design:
class Node{
public:
std::string name;
Node* next = nullptr;
};
class linkedBotList{
public:
linkedBotList() = default;
~linkedBotList();
void addNode(std::string name);
void display() const;
private:
Node* head = nullptr;
Node* tail = nullptr;
};
int main() {
linkedBotList list;
int siz;
std::string botName;
std::cout << "How many Robots?" << std::endl;
std::cin >> siz;
std::cout << "What are the names?" << std::endl;
for(int i = 0; i < siz; i++){
std::cin >> botName;
list.addNode(botName);
}
list.display();
return 0;
}
linkedBotList::~linkedBotList(){
Node *temp = head, *next;
while (temp) {
next = temp->next;
delete temp;
temp = next;
}
}
void linkedBotList::addNode(std::string name){
Node* newNode = new Node{name};
if (tail)
tail->next = newNode;
else
head = newNode;
tail = newNode;
}
void linkedBotList::display() const {
if (!head) {
std::cout << "List is empty!" << std::endl;
}
else {
Node* temp = head;
do {
std::cout << temp->name << " ";
temp = temp->next;
}
while (temp);
std::cout << std::endl;
}
}
|
74,486,364
| 74,486,622
|
Why capacity of std::string is 15. Why my reserve() is ignored?
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
s.reserve(5);
cout << s.capacity() << endl;
}
The reserve is a std::string's function that sets the capacity. The capacity function shows the space size of c_string in the std::string.
But, the result is not 5, but 15. I don't know why.
|
Note that also
int main()
{
std::string s;
std::cout << s.capacity() << "\n";
s.reserve(5);
std::cout << s.capacity() << "\n";
}
Would print 15 twice.
Consider the output of this
#include <iostream>
#include <string>
int main()
{
std::string s;
std::cout << s.capacity() << "\n";
std::cout << sizeof(std::string) << "\n";
std::cout << sizeof(char) << "\n";
std::cout << sizeof(char*) << "\n";
std::cout << sizeof(size_t) << "\n";
}
Possible output:
15
32
1
8
8
A std::string somehow has to store the character array, its size, capacity and perhaps some more bookkeeping. The obvious way to store a character array is with a char* and a size_t for the size (only null-terminator is not sufficient for constant time size() and others). However, thats 16 bytes. A single character is only 1 byte. Hence an empty std::string before allocating any dynamic memory has enough space to store some characters by reusing memory that is used for other stuff once the string grows.
Thats is short string optimization. I only outlined the general idea. For details I refer you to other resources or the implementation.
Further reserve(n) will only make sure that the string has enough space for at least n characters. An empty string already has enough space to store 5 characters. When n is smaller than the current capacity the string might shrink or not (it does not since C++20).
TL;DR: Your call to reserve is not ignored. After the call the string has enough capacity to hold 5 characters. The initial capacity on your implementation seems to be 15. It could be some other value as well.
|
74,486,584
| 74,486,753
|
Is using std::numeric_limits<T>::quiet_NaN() a bad practice?
|
Have the following function that searches a query for a match and returns NaN if no match was found:
int64_t Foo::search(const std::string& foo, int64_t t0, ...
if {
...
}
else
return std::numeric_limits<int64_t>::quiet_NaN();
}
|
std::numeric_limits<T>::quiet_NaN(); is only meaningful if T is a floating point type for which std::numeric_limits<T>::has_quiet_NaN(); is true. So, no, your code is not good practise.
Reference: https://en.cppreference.com/w/cpp/types/numeric_limits/quiet_NaN
|
74,486,919
| 74,497,389
|
Is it legal to use std::declval in lambda in unevaluated contexts?
|
Code as below or on godbolt compiles with gcc and MSVC but fails with clang. I couldn't find if/where it is forbidden in the standard. In my opinion it should be supported.
So who is correct on this, clang or gcc/MSVC?
#include <type_traits>
void foo() {
static_assert(decltype([_=std::declval<int>()]() consteval noexcept { // clang error: declval() must not be used
if constexpr (std::is_integral<decltype(_)>::value) {
return std::bool_constant<true>();
} else {
return std::bool_constant<false>();
}
}())::value);
}
The example could be expanded into 3 cases as below or on godbolt:
as lambda call argument: OK with clang/gcc/MSVC
as lambda capture: OK with gcc/MSVC, error with clang
in lambda body: error with clang/gcc/MSVC
So it seems clear that it is not legal in lambda body but legal outside as caller argument. It is not clear if it is allowed in capture list.
#include <type_traits>
auto foo_lambda_argument() {
return decltype([](auto _) noexcept {
return std::bool_constant<std::is_integral<decltype(_)>::value>();
}(std::declval<int>()))::value; // OK with clang/gcc/MSVC
}
auto foo_capture_list() {
return decltype([_=std::declval<int>()]() noexcept { // OK with gcc/MSVC; clang error: declval() must not be used
return std::bool_constant<std::is_integral<decltype(_)>::value>();
}())::value;
}
auto foo_lambda_body() {
return decltype([]() noexcept {
auto _=std::declval<int>(); // clang/gcc/MSVC error
return std::bool_constant<std::is_integral<decltype(_)>::value>();
}())::value;
}
|
I am not completely sure how this is intended to work, but here is my attempt at a solution:
According to [intro.execution]/3.3 the initializer of an init-capture is an immediate subexpression of a lambda expression. However none of the listed items make the expressions in the lambda's body subexpressions.
Unevaluated operands are non-potentially-evaluated expressions. But only their subexpressions are also non-potentially-evaluated expressions. (see [basic.def.odr]/2)
A function is odr-used if it is named by a potentially-evaluated expression or in some special cases that are not relevant here.
So std::declval should be fine in the init-capture initializer as in your point 2.
It is also ok in point 1, because the function arguments are subexpressions of the function call expression making up the whole unevaluated operand.
Point 3 is not ok, because the expressions in the body of the lambda are potentially-evaluated even if the lambda expression appears in an unevaluated operand.
One concern I have with the reasoning above is that [exp.prim.lambda.capture]/6 specified an init-capture to behave as if declaring a variable with the given intializer and then capturing it. I am not sure where this fits into the above (the declaration couldn't be a subexpression) and whether it would count as odr-use.
|
74,487,257
| 74,510,835
|
Python/C++ Extension, Undefined symbol error when linking a library
|
I made a project that has glfw as a library, my directory looks like this:
main_dir
|--include
|--|--glfw_binder.h
|--src
|--|--glfw_binder.cpp
|--lib
|--|--glfw
|--|--|--src
|--|--|--|--libglfw.so
|--|--|--|--libglfw.so.3
|--|--|--|--libglfw.so.3.3
|--|--|--|--...
|--|--|--include
|--|--|-- ...
|--main.cpp
|--setup.py
|--test.py
I've installed glfw from its website and simply extracted it to lib/ directory. Then I ran cmake -G "Unix Makefiles" followed by make to build it.
When I try to run it as pure C++ with this cmake file it runs just fine, it displays the glfw window:
cmake_minimum_required(VERSION 3.0)
project(Test)
add_subdirectory(lib/glfw)
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
add_executable(Test main.cpp src/glfw_binder.cpp)
target_link_libraries(Test PRIVATE
${PYTHON_LIBRARIES}
glfw
)
And here is what my setup.py looks like:
from setuptools import setup, Extension, find_packages
module1 = Extension('test',
sources = ['main.cpp', 'src/glfw_binder.cpp'],
include_dirs=["include", "lib/glfw/include"],
library_dirs=["lib/glfw"],
libraries=["lib/glfw"],
extra_link_args=["lib/glfw"]
)
setup (name = 'python_test',
version = '1.0',
description = 'This is a demo package',
packages=find_packages("glfw"),
ext_modules = [module1]
)
Then I run python3 setup.py build followed by sudo python3 setup.py install. It creates the so files just fine. Then I run this test code:
import test
test.create_glfw_window()
When I run this script via python3 test.py I got this error:
Traceback (most recent call last):
File "/home/turgut/Desktop/TestDir/Python-Binder-Test/test.py", line 3, in <module>
import test
ImportError: /usr/local/lib/python3.10/dist-packages/python_test-1.0-py3.10-linux-x86_64.egg/test.cpython-310-x86_64-linux-gnu.so: undefined symbol: glfwDestroyWindow
It's not specific to glfwDestroyWindow it says this for all glfw functions. How am I supposed to link this?
Update: I've added these lines:
packages=['glfw'],
package_dir={'glfw': 'lib/glfw'},
#package_data={'glfw': ['lib/glfw/src/*.so']},
package_data={'glfw': ['lib/glfw/src/libglfw.so', "lib/glfw/src/libglfw.so.3", "lib/glfw/src/libglfw.so.3.3"]},
Now it gives me the following error:
ImportError: libglfw.so.3: cannot open shared object file: No such file or directory
Even though I've specified all the .so files together. I don't think this is the way to go but I thought it's worth mentioning.
Better update:
I've removed the above update and added these two lines to my extension:
include_dirs=["include", "lib/glfw/include"],
#extra_link_args=[ "-lm", "-lGL", "-lGLU", "-lglfw"],
library_dirs=["lib/glfw"],
libraries=['glfw']
and now I'm getting this error which I think is closer to what I'm looking for:
/usr/bin/ld: cannot find -lglfw: No such file or directory
collect2: error: ld returned 1 exit status
error: command '/usr/bin/x86_64-linux-gnu-g++' failed with exit code 1
|
For anyone facing a similar issue, you need to specify runtime_library_dirs so the setup.py file looks like this:
from setuptools import setup, Extension, find_packages
module1 = Extension('nerveblox',
sources = ['main.cpp', 'src/nerveblox_VM.cpp'],
include_dirs=["include", "lib/glfw/include"],
#extra_link_args=[ "-lm", "-lGL", "-lGLU", "-lglfw"],
library_dirs=["lib/glfw/src"],
libraries=['glfw', 'GL'],
runtime_library_dirs=['lib/glfw/src']
)
setup (
name = 'Nerveblox_python_test',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1],
install_requires=[
'importlib-metadata; python_version == "3.8"',
],
)
|
74,487,512
| 74,488,174
|
Is memory leak possible, when I directly change the char array in std::string by accessing the address of it?
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
char* c = &s[0];
c[0] = '4';
c[1] = '3';
c[2] = '\0';
cout << s.data();
}
You can access the char array inside a string like this. But, I think that it is undefined behavior. This behavior make that many features of the string are not worked.
What I'm wondering is, is there any possible of a memory leak because of this approach?
|
Yes, you're right that it is Undefined Behavior. With Undefined Behavior, anything can happen. That does include "memory leak", which can occur in isolation or in combination with any other symptom.
Of course, "memory leak" isn't that important when the other problems happening are "crash" or "computer on fire". So just add an s.resize(3). That solves the UB.
|
74,487,559
| 74,487,666
|
(C++) Calculating [(1! / 1^1) + (2! / 2^2) + ... + (20! / 20^20)] with using subfunctions of factorial and power
|
#include <iostream>
using namespace std;
int power(int a, int b); // Subfunction to calculate a^b
int fact(int c); // Subfunction to calculate factorial
int main() {
int x=0;
for(int i=1 ; i<=20 ; i++)
x+= fact(i) / power (i,i); // needs to calculate like [(1! / 1^1) + (2! / 2^2) + (3! / 3^3) + ...... + (20! / 20^20) // assigned x and sum it with counter to calculate final result
cout<<x;
return 0;
}
int power(int a, int b) { // a^b subfunction
unsigned long long int multip=1; // written the biggest type just in case (idk if i need it)
for (int i=1; i<=b; i++) {
multip*=a;
}
return multip;
}
int fact(int c) { // factorial subfunction
unsigned long long int multip=1;
for (int i=c ; i>=1 ; i--) {
multip*=i;
}
return multip;
}
I tried to calculate [(1! / 1^1) + (2! / 2^2) + ... + (20! / 20^20)] but somewhy program didn't work at all. output
I'm sorry if the mistake is obvious I've been trying for long hours and can't think much right now. I will return to the replies with fresh head.Have a good day.
|
You have some serious problems with your types:
int power(...);
int fact(...);
=> this should be long long.
In top of this, you are doing integer division, while you need floating point division:
fact(i) / power (i,i);
... should be:
((double) fact(i)) / power (i,i);
|
74,487,601
| 74,487,704
|
LINKED LIST: Why do I need to "return;" in the if statement...even if i'm passing head by reference in the function(to add node at end)
|
#include<iostream>
using namespace std;
class node{
public:
int data;
node* addr;.//it's address of the next node
node(int val){
data=val;
addr = NULL;
}
};
void addVal(node* &head, int val){
node *n=new node(val);
if (head==NULL){
head = n;
return;///<-WHY THIS?
}
node *p=head;
while(p->addr!=NULL){
p=p->addr;
}
p->addr=n;
return;
}
void display(node *head){
node *p=head;
while(p!=NULL){
cout<<p<<" "<<p->data<<" "<<p->addr<<endl;
p=p->addr;
}
}
int main(){
node *head=NULL;
addVal(head,1);
addVal(head,2);
addVal(head,3);
addVal(head,4);
addVal(head,5);
display(head);
return 0;
}
I was getting a blank terminal when I ran this without the return; inside of the if statement. Why is return necessary here? (I passed head's val by reference, so if I change it inside of the function the actual value would be affected as usual. But somehow it gets stuck without the return).
|
If you do not return this is what happens:
node *p=head; // p equals head which equals n
while(p->addr!=NULL){ // p->addr is NULL, this loop stops immediately
p=p->addr;
}
p->addr=n; // this assignes n to p's next ptr
return;
The use of many different names for the same thing can be a little confusing. You create a new node and the pointer to it is n. This is the new head. p also points to this new head.
Now addr is the next node of head.
If you do not return after creating the new head and assigning the pointer to head the function will continue to assing the pointer to the same node to head->addr. You'd get a list with a head that has itself as the next node.
You could have observed this by using a debugger.
|
74,487,769
| 74,488,262
|
Initialize custom collection with list of values
|
I have created a class that should act as a collection (with some custom behavior of mine).
Inside, the class contains an array, to store the values.
class MyCollection {
private:
int m_array[N];
public:
int operator [] (int idx) const {
return m_array[idx];
}
int operator [] (TKey k) {
return m_array[idx];
}
};
I would like to be able to initialize an instance of this class like it can be done with arrays, but I don't know how to do it, or what this kind of initialization is called ot then look on the web.
std::array<int, 3> a2 = {1, 2, 3};
How can this be achieved?
Please note that I may change the type of the elements of the collection (even template it), the referred int is just an example.
|
The std::initializer_list will be your friend.
We can add it in a constructor, but also in an assignment operator, or any other member function.
Please read about it here.
Code could look like:
#include <iostream>
#include <initializer_list>
class MyCollection {
private:
int m_array[10]{};
public:
MyCollection(const std::initializer_list<int> il) {
if (il.size() <= 10) {
size_t i{};
for (const int& t : il) m_array[i++] = t;
}
}
int operator [] (size_t idx) const {
return m_array[idx];
}
};
int main() {
MyCollection mc {1,2,3,4,5,6,7,8,9,10};
for (size_t i{}; i < 10; ++i)
std::cout << mc[i] << '\n';
}
|
74,489,031
| 74,489,078
|
Why don't define some undefined behaviours?
|
What are the reasons for C++ to not define some behavior (something like better error checking)? Why don't throw some error and stop?
Some pseudocodes for example:
if (p == NULL && op == deref){
return "Invalid operation"
}
For Integer Overflows:
if(size > capacity){
return "Overflow"
}
I know these are very simple examples. But I'm pretty sure most UBs can be caught by the compiler. So why not implement them? Because it is really time expensive and not doing error checking is faster? Some UBs can be caught with a single if statement. So maybe speed is not the only concern?
|
Because the compiler would have to add these instructions every time you use a pointer. A C++ program uses a lot of pointers. So there would be a lot of these instructions for the computer to run. The C++ philosophy is that you should not pay for features you don't need. If you want a null pointer check, you can write a null pointer check. It's quite easy to make a custom pointer class that checks if it is null.
On most operating systems, dereferencing a null pointer is guaranteed to crash the program, anyway. And overflowing an integer is guaranteed to wrap around. C++ doesn't only run on these operating systems - it also runs on other operating systems where it doesn't. So the behaviour is not defined in C++ but it is defined in the operating system.
Nonetheless, some compiler writers realized that by un-defining it again, they can make programs faster. A surprising amount of optimizations are possible because of this. Sometimes there's a command-line option which tells the compiler not to un-define the behaviour, like -fwrapv.
A common optimization is to simply assume the program never gets to the part with the UB. Just yesterday I saw a question where someone had written an obviously not infinite loop:
int array[N];
// ...
for(int i = 0; i < N+1; i++) {
fprintf(file, "%d ", array[i]);
}
but it was infinite. Why? The person asking the question had turned on optimization. The compiler can see that there is UB on the last iteration, since array[N] is out of bounds. So it assumed the program magically stopped before the last iteration, so it didn't need to check for the last iteration and it could delete the part i < N+1.
Most of the time this makes sense because of macros or inline functions. Someone writes code like:
int getFoo(struct X *px) {return (px == NULL ? -1 : px->foo);}
int blah(struct X *px) {
bar(px->f1);
printf("%s", px->name);
frobnicate(&px->theFrob);
count += getFoo(px);
}
and the compiler can make the quite reasonable assumption that px isn't null, so it deletes the px == NULL check and treats getFoo(px) the same as px->foo. That's often why compiler writers choose to keep it undefined even in cases where it could be easily defined.
|
74,489,355
| 74,489,909
|
Function was put into a curly bracket in order to initialize the member in class. What is its syntax?
|
The code is shown here:
class Basket{
public:
/*other contents*/
private:
// function to compare shared_ptrs needed by the multiset member
static bool compare(const std::shared_ptr<Quote> &lhs,
const std::shared_ptr<Quote> &rhs)
{ return lhs->isbn() < rhs->isbn(); }
// multiset to hold multiple quotes, ordered by the compare member
std::multiset<std::shared_ptr<Quote>, decltype(compare)*>
items{compare};
};
We initialize our multiset through an in-class initializer. Commonly we put a same class object in the curly bracket. Why a function can be put here? I can't understand;
It's explained in the book C++ primer like it: The multiset will use a function with the same type as our compare member to order the elements. The multiset member is named items, and we’re initializing items to use our compare function.
I can understand the logic, but what is the syntax used here?
|
items{compare}; is a call to one of the overloads of the constructor of std::mulitset.
Which one of the overloads to use is decided by the compiler from looking at your argument type: compare matches the description of a "comparison function object" (see link), so the second invocation is used.
It is a pointer to a function, taking two values as parameters and returning a boolean is the main point here. That function can then be later called by the multiset object to sort its members.
Look up "callback functions" if you want to learn more about this concept. See here for a start: Callback functions in C++
What you're refering to with
Commonly we put a same class object in the curly bracket.
would be using the copy-constructor (no. 6 in the link). Just another way to create the same type of object.
There are questions here on SO about using a constructor with {} vs () if that is part of the confusion:
What's the difference between parentheses and braces in c++ when constructing objects
|
74,489,412
| 74,528,835
|
OpenCV 4.5.3, C++, OpenCL "Transparent API", UMat instead Mat, no improvements
|
my C++ code is running on Win 10, self built OpenCV 4.5.3., WITH_OPENCL flag checked.
Using UMat instead of Mat does not result in any performance improvements through "Transparent API" of OpenCL.
From what I have read on https://jeanvitor.com/opencv-opencl-umat-performance/ i expected at least a slight performance improvement when using UMat instead of Mat even on my notebooks Intel HD Graphics 520.
executing resize, cvtColor, and bilateralFilter for UMat and Mat does not show any difference.
ocl::haveOpenCL and ocl::useOpenCL both return true.
queried values for the only Device::TYPE_GPU device are:
name: Intel(R) HD Graphics 520
extensions: cl_khr_3d_image_writes cl_khr_byte_addressable_store cl_khr_fp16 cl_khr_depth_images cl_khr_global_int32_base_atomics cl_khr_global_int32_extended_atomics cl_khr_icd cl_khr_image2d_from_buffer cl_khr_local_int32_base_atomics cl_khr_local_int32_extended_atomics cl_intel_subgroups cl_intel_required_subgroup_size cl_intel_subgroups_short cl_khr_spir cl_intel_accelerator cl_intel_media_block_io cl_intel_driver_diagnostics cl_intel_device_side_avc_motion_estimation cl_khr_priority_hints cl_khr_throttle_hints cl_khr_create_command_queue cl_khr_fp64 cl_khr_subgroups cl_khr_il_program cl_khr_mipmap_image cl_khr_mipmap_image_writes cl_intel_planar_yuv cl_intel_packed_yuv cl_intel_motion_estimation cl_intel_advanced_motion_estimation cl_khr_gl_sharing cl_khr_gl_depth_images cl_khr_gl_event cl_khr_gl_msaa_sharing cl_intel_dx9_media_sharing cl_khr_dx9_media_sharing cl_khr_d3d10_sharing cl_khr_d3d11_sharing cl_intel_d3d11_nv12_media_sharing cl_intel_simultaneous_sharing
version: OpenCL 2.1 NEO
OpenCLVersion: OpenCL 2.1 NEO
OpenCL_C_Version: OpenCL C 2.0
have also tried that on other machines, no difference in performance.
what am i missing, any ideas or hints?
|
found out that the issue was caused by the Microsoft Unit Testing Framework for C++. in my production code using UMat is way faster than Mat.
question answered
|
74,489,766
| 74,490,057
|
How to use an abstract class rvalue reference member?
|
I have an abstract class Base and derived class Derived:
class Base
{
public:
Base(int n) :_n(n) { _arr = new int[n]; }
virtual ~Base() { delete[] _arr; }
Base(Base&& other) { _n = other._n; _arr = other._arr; other._arr = nullptr; other._n = 0; }
virtual void func() = 0;
private:
int _n;
int* _arr;
};
class Derived : public Base
{
public:
Derived(int m, int n) : Base(n), _m(m) { _arr = new int[m]; }
~Derived() { delete[] _arr; }
Derived(Derived&& other) : Base(std::move(other)) { _m = other._m; _arr = other._arr; other._arr = nullptr; other._m = 0; }
void func() override { cout << "func"; }
private:
int _m;
int* _arr;
};
Then I have a class Bag which contains a rvalue reference of Base:
class Bag
{
public:
Bag(Base&& b) : _b(std::move(b)) {}
void func() { _b.func(); }
private:
Base&& _b;
};
int main()
{
Bag bag(Derived(1, 1));
bag.func();
}
I use a rvalue reference member _b because I just want to take a temporary object in Bag's constructor. However, after bag.func() I got an error: abort() is called. It seems that bag._b's type changes from Derived to Base after the temporary object Derived(1,1) is destructed.
bag.func() works after I delete virtual ~Base() { delete[] _arr; }. Why? If I need Base's destructor, how can I change my code?
|
Base&& _b is a reference to the temporary object, when that temporary is destroyed at the end of the line Bag bag(Derived(1, 1)); the reference becomes a dangling reference and any use of the reference is undefined behaviour.
You could change _b to a value instead but that would slice your object.
If you want to store a polymorphic object the only real option is to use a pointer (ideally a smart one). For example:
class Bag
{
public:
Bag(std::unique_ptr<Base>&& b) : _b(std::move(b)) {}
void func() { _b->func(); }
private:
std::unique_ptr<Base> _b;
};
int main()
{
Bag bag(std::make_unique<Derived>(1, 1));
bag.func();
}
Note that you should also ensure that Base and Derived follow the rule of five otherwise you may encounter issues when you assign objects.
|
74,489,862
| 74,513,942
|
WinUI3 : Understanding WinUI3 desktop app
|
As we can create a WinUI3 app in both the desktop app(win32 app) and the UWP app. What exactly does it mean to create a WinUI3 in a desktop app? As I understand, this app will follow the Win32 App model, that is, the app will not run on sandbox and the app will not have activation and lifecycle management like UWP apps. Is this right?
In this case, How can we use Win32 APIs in this project, and can we follow the event loop like the WNDPROC callback function instead of Application::Start()?
Thank You
|
I found that you have posted the same case on the Q&A forum: https://learn.microsoft.com/en-us/answers/questions/1095079/winui3-understanding-winui3-desktop-app.html
You could refer to the answer provided by Castorix 31. To prevent the link from expiring, I will post the answer to Castorix 31:
Application::Start replaces the main message loop.
As it is a Win32 app, you can have access to the main window WndProc with
SetWindowSubclass.
|
74,490,868
| 74,491,142
|
CMakeLists includeT Qt5::QML does not work
|
This is my CMakelists.txt file.
cmake_minimum_required(VERSION 3.0.2)
project(osm_map)
find_package(catkin REQUIRED COMPONENTS rviz)
find_package(Qt5 COMPONENTS Widgets REQUIRED)
set(QT_LIBRARIES Qt5::Widgets Qt5::Qml)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set(SRC_FILES
src/core.cpp
)
add_library(${PROJECT_NAME} ${SRC_FILES})
target_link_libraries(${PROJECT_NAME} ${QT_LIBRARIES} ${catkin_LIBRARIES})
When I try to compile my project with catkin_make -Wno-dev --only-pkg-with-deps osm_map, it seems to find every module of QT (I also tested others not shown below) but not QML. Error message:
CMake Error at osm_map/CMakeLists.txt:53 (target_link_libraries):
Target "osm_map" links to:
Qt5::Qml
but the target was not found. Possible reasons include:
* There is a typo in the target name.
* A find_package call is missing for an IMPORTED target.
* An ALIAS target is missing.
QT QML is installed on my system and the path /usr/include/x86_64-linux-gnu/qt5/QtQml and includes the necessary headers. And idea why I could do? The find_package call for QT is supposed to find all libaries and headers shipped with QT, maybe that is the part that is not working properly for QML?
|
The problem is in your
find_package(Qt5 COMPONENTS Widgets REQUIRED)
here you asked CMake that you wanted the Widgets component of Qt5 but then you tell it to link with Qml which you did not ask for.
You should change this to the following:
find_package(Qt5 COMPONENTS Widgets Qml REQUIRED)
|
74,490,925
| 74,491,133
|
Accessing a pointer to a derived class when it is not created
|
Why referring to a pointer to a derived class that has not yet been created is valid, but not undefined behavior.
godbolt.org
#include <iostream>
struct A{
int a;
void foo() {
std::cout << "A = " << a << std::endl;
}
};
struct B : public A{
int b;
void foo() {
std::cout << "B = " << b << std::endl;
}
};
int main() {
A *a = new A();
B *b = static_cast<B*>(a);
a->foo(); // cout A = 0
b->foo(); // cout B = 0
b->b = 333;
b->foo(); // cout B = 333
a->foo(); // cout A = 0
}
Should a pointer to a derived class be undefined?
|
Compile with -O3 -Werror -Wall to get the following message from gcc:
<source>: In function 'int main()':
<source>:25:8: error: array subscript 'B[0]' is partly outside array bounds of 'unsigned char [4]' [-Werror=array-bounds]
25 | b->b = 333;
| ~~~^
<source>:19:18: note: object of size 4 allocated by 'operator new'
19 | A *a = new A();
| ^
cc1plus: all warnings being treated as errors
The message is somewhat funny, becuase it leaks some gcc implementation details by mentioning a unsigned char [4] when there is none. However, if you consider what is wrong in your code, the message nails it....
In memory, a B object looks like this (very simplified):
A
B
It has an A subobject and after that comes the B members. Now it happens that A is of size 4 (could be different but thats what it is with gcc).
When you write b->b. Then b points to an A (not to ba B), but you pretend that it does point to a B. Hence when the compiler tries to apply the offset to the pointer to reach the member, this offset is larger than the size of the object. The compiler realizes that something cannot be right.
However, this is error message nothing more than an interesting curiosity. The compiler is not required to diagnose your mistake because your code has undefined behavior.
When your code has undefined behavior, anything can happen. The worst case is that the code appears to be fine and work as expected.
Why does your code compile and work ok? It does not. b does not point to a B. Your code could print "Hello World" to the console as well, it could erase your hard drive or really anything could happen. Only if your code has no undefined behavior there is a guarantee what your program will do.
|
74,491,271
| 74,491,838
|
Double free in c++ destructor
|
I'm trying to implement a linked list in C++. The list contains a pointer to a node type allocated on the heap
The code is as follow:
#include <memory>
template<typename T>
class node {
public:
node(T v) : value(v) {}
~node() = default;
T value;
node *next;
};
template<typename T, class Allocator = std::allocator<node<T>>>
class linked_list {
private:
node<T>* head;
Allocator alloc;
public:
linked_list() : head(nullptr) {}
~linked_list() {
for (auto start = head; start != nullptr; start = start->next) {
start->~node();
alloc.deallocate(start, 1);
}
}
void push_back(T value) {
node<T> *new_node = alloc.allocate(1);
new (new_node) node<T>(value);
if (head == nullptr) {
head = new_node;
return;
}
head->next = new_node;
head = new_node;
}
};
In main.cpp:
#include "linked_list.hpp"
int main() {
linked_list<int> a;
a.push_back(4);
a.push_back(5);
return 0;
}
When I ran it I got double free detected in cache T2.
What did I do wrong with the destructor ?
|
This is a common newbie error. You modified your loop control variable.
for (auto start = head; start != nullptr; start = start->next)
{
start->~node();
alloc.deallocate(start, 1);
}
You modified start (deleting the memory) in the for loop's body and then tried to dereference the pointer you just deleted in its continuation expression. BOOM! You are fortunate that the runtime library was smart enough to catch this and give you the "double free" error rather than, say, launch a nuclear missile.
This is one place a while loop is better than a for loop.
while (head)
{
auto to_del = head;
head = head->next;
to_del ->~node();
alloc.deallocate(to_del, 1);
}
I've left out a lot of commentary about your antiquated techniques because they don't relate to the problem you're having, but if you really want to substitute in a different kind of allocator you should look into using allocator_traits for allocation, construction, destruction, and deallocation of your elements.
There are other problems, such as push_back being completely wrong as to where it inserts the new node. Replacing head->next = new_node; with new_node->next = head; will at least keep your program from orphaning all of the new nodes.
|
74,491,731
| 74,491,878
|
Constexpr evaluation and compiler optimization level
|
see the following snippet:
struct config {
int x;
constexpr int multiply() const {
return x*3;
}
};
constexpr config c = {.x = 1};
int main() {
int x = c.multiply();
return x;
}
If I compile this with clang and -O0 I get a function call to multiply even though the object c and the function are marked constexpr. If I compile it with -O1 everything gets optimized as expected. Gcc on the other hand generates no call to multiply.
If I change the main to:
int main() {
constexpr auto y = c.multiply();
int x = y;
return x;
}
If I compile this with clang and -O0 I get not function call and the value 3 directly as stack variable. The -O1 result is the same as above.
So my question is: Does the constexpr evaluation depend on the compiler level? I would expect that in the example 1 the call to multiply would be constexpr and performed compile time. (like gcc does)
BR,
go2sh
See https://godbolt.org/z/WvPE5W77h
|
The Standard just requires that a call to constexpr is evaluated at compile time if the arguments are constexpr and the result must be constexpr due to context. Basically just forcing more restrictions on the author of the function, thus allowing it to be used in constexpr contexts.
Meaning y in second snippet forces evaluation at compile time. On the other hand, x in the first is an ordinary run-time call.
But the as-if rule applies here - as long as the observable effects of the program remain the same, the compiler can generate any instructions it wants. It can evaluate any function, even non-constexpr ones if it can do so - happens in practice often with constants propagation.
Yes, in general, higher optimization levels will inline more code and push more evaluation to the compile time. But "looking at the assembly" is not an observable effect in the sense above so there are no guarantees. You can use inline to give a hint for inlining the function instead of calling it (constexpr is inline by default but for other reasons...) but the compilers can ignore them.
Of course, the compiler can evaluate all constexpr functions with constexpr args at compile time, that is why they exist, why clang does not do so with -O0, I do not know.
If you need guaranteed compile-time evaluation, use consteval instead.
|
74,492,635
| 74,493,368
|
Is there a sugar syntax for usings in CPP? Like using std::{name1, name2, ..., nameN}?
|
Let's say I want to use
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
But I don't want to use
using namespace std;
Is there something like this:
using std::{cout, cin, endl};
I've tried
using std::{cout, cin, endl};
Instead I got a syntax error.
|
As of c++17, you can add multiple objects in using separated by a comma.
using std::vector, std::cout, std::cin;
Previously it required a separate using statement for each. See the using declaration . You do have to include the full path for each declaration.
|
74,493,270
| 74,493,331
|
What is the use of a private init() member function?
|
EDIT for more details: this is a school assignment and the private variables/functions of the Time class were given to me already. I have to declare and define a member function which adds two Times together and saves the result in the Time member variable of another class. I'm not sure what the assignment intends me to do with the given init() function.
Say I have a class Time:
class Time {
public:
Time();
Time(int hours, int mins, int secs);
// public member functions here
friend std::ostream& operator << (std::ostream&, Time&);
private:
int theHour;
int theMins;
int theSecs;
void init(int hours, int minutes, int seconds);
};
I know one thing I'll have to do when creating a Time object from hours/mins/secs values before setting hours = theHour, mins = theMins, secs = theSecs is check that the values for hours/mins/secs are valid. However, I already have a constructor Time(int hours, int mins, int secs); which I was thinking of defining as follows:
Time::Time(int hours, int mins, int secs)
{
if ((hours < 0) || (mins < 0) || (secs < 0) || (hours > 60) || (mins > 60) || (secs > 60))
{
cout << "Illegal time value.\n";
exit(1)
}
hours = theHour;
mins = theMins;
secs = theSecs;
}
If I already have a constructor to initialise an instance of hours, mins, secs as a time object and check for illegal values, what is the point of the void init() function?
|
This is an old C++ style. It allows multiple constructors to share code.
Modern C++ would use
Time::Time() : Time(0,0,0) { }
which reuses the existing 3-argument ctor.
|
74,494,340
| 74,494,929
|
Delete duplicated in a linked list solution from C++ to rust
|
I have this code solution written in c++ for the problem remove-duplicates-from-sorted-list and just now I'm learning rust and I want to build the same solution in rust programming language my rust linkedList doesn't have ListNode have Option<Box<Node>>
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return head;
ListNode* current = head;
while (current->next) {
if (current->next->val == current->val)
current->next = current->next->next;
else
current = current->next;
}
return head;
}
};
If you know the rust way for write my c++ solution please share it with me and thank you for your help.
|
impl Solution {
pub fn delete_duplicates(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
by matching instead of just checking for .is_none() we can get the value inside
& check for None at the same time.
// if (!head) return head;
// ListNode* current = head;
let mut current = match head.as_mut() {
Some(c) => c,
None => return head,
};
Then we take the next item while checking it's there.
By using .take() we avoid having 2 mutable borrows of current, we'll also clean up the memory this way.
// while (current->next) {
while let Some(mut rest) = current.next.take() {
// if (current->next->val == current->val)
if rest.val == current.val {
// current->next = current->next->next;
current.next = rest.next;
} else {
// since we took earlier we gotta put it back
current.next = Some(rest);
// current = current->next;
// unwrap is perfectly fine since we just set it to Some(rest)
current = current.next.as_mut().unwrap();
}
}
return head;
}
}
.as_mut() is just a way to turn a &mut Option<T> into Option<&mut T>
|
74,494,375
| 74,525,478
|
Inverting a sparse matrix using eigen
|
I'm trying to use a sparse solver as SimplicialLLT to inverse a symmetric positive-definite matrix and return it.
I get a matrix from R using Rcpp to connect R and cpp, I take this matrix as an argument of the function cpp_sparse_solver, use sparseView() to turn it to SparseMatrix, declare the solver, compute and solve the system with an identity matrix as argument to invert it. However, I get the error "Eigen::MatrixXd is not a template". I'm not an expert at cpp, so I'd like some tips about possible mistakes.
#include <cmath>
#include <Rcpp.h>
#include <RcppEigen.h>
#include <stdio.h>
#include <R.h>
#include <Rmath.h>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <Eigen/OrderingMethods>
#include <Eigen/SparseCholesky>
using namespace Eigen;
using namespace Rcpp;
using namespace std;
// [[Rcpp::depends(RcppEigen)]]
//' Inverts matrices inside cpp
//' @param matrix Matrix to be inverted
//' @export
// [[Rcpp::export]]
MatrixXd cpp_sparse_solver(Eigen::MatrixXd<double> matrix){
// START
// Declaring objects
int n = matrix.rows();
MatrixXd I = Matrix<double, n, n>::Identity();
matrix_s = matrix.sparseView();
SimplicialLLT<Eigen::SparseMatrix<double>, Lower, NaturalOrdering<int>> solver;
matrix_s.makeCompressed();
solver.compute(matrix_s);
MatrixXd Ainv = solver.solve(I);
return Ainv;
}
|
There were a number of things wrong in your code, and a few other stylistic things I would do differently. Below is version which actually compiles and it differs in having
reduced the number of headers to the single one you need
removed the namespace flattening statements which mostly cause trouble
updated some types
Code
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
//' Inverts matrices inside cpp
//' @param matrix Matrix to be inverted
//' @export
// [[Rcpp::export]]
Eigen::MatrixXd cpp_sparse_solver(Eigen::MatrixXd matrix){
int n = matrix.rows();
Eigen::MatrixXd I = Eigen::MatrixXd::Identity(n,n);
Eigen::SparseMatrix<double> matrix_s = matrix.sparseView();
Eigen::SimplicialLLT<Eigen::SparseMatrix<double>, Eigen::Lower,
Eigen::NaturalOrdering<int>> solver;
matrix_s.makeCompressed();
solver.compute(matrix_s);
Eigen::MatrixXd Ainv = solver.solve(I);
return Ainv;
}
|
74,494,530
| 74,495,745
|
How to copy a vector of A to a vector of A pointer using std algorithms?
|
I've got a std::vector<Edge> edges and I'd like to copy some items from this array into a std::vector<Edge*> outputs using std library.
I know std::copy_if can be used to copy a vector of pointers to a vector of pointers:
std::vector<Edge*> edges;
//setup edges
std::vector<Edge*> outputs;
std::copy_if(edges.cbegin(), edges.cend(), std::back_insert_iterator<decltype(outputs)>(outputs), [](auto edge) {
return true; //here should be some condition
});
but it's not possible to do this:
std::vector<Edge> edges;
//setup edges
std::vector<Edge*> outputs;
std::copy_if(edges.cbegin(), edges.cend(), std::back_insert_iterator<decltype(outputs)>(outputs), [](auto edge) {
return true; //here should be some condition
});
I understand why it's not possible.
My question is:
Is there any algorithm that would let me do this?
|
You can use Eric Niebler's range-v3 library:
get the input vector,
filter out some of its elements,
transform the remainder into pointers to them, and
convert that view to a vector of pointers.
[Demo]
#include <iostream>
#include <range/v3/all.hpp>
#include <vector>
struct Edge {
int value;
};
int main() {
std::vector<Edge> edges{ {-10}, {-5}, {2}, {4} };
auto outputs = edges
| ranges::views::filter([](auto& e){ return e.value > 0; })
| ranges::views::transform([](auto& e) { return &e; })
| ranges::to<std::vector<Edge*>>();
for (const auto o : outputs) {
std::cout << o->value << " ";
}
}
// Outputs: 2 4
Wouldn't you need to create an output vector, you could get along by using C++20 ranges (std::ranges::to will also be available at some point for C++23).
[Demo]
#include <iostream>
#include <ranges>
#include <vector>
struct Edge {
int value;
};
int main() {
std::vector<Edge> edges{ {-10}, {-5}, {2}, {4} };
auto&& outputs{ edges
| std::views::filter([](auto& e){ return e.value > 0; }) };
for (auto&& o : outputs) {
std::cout << o.value << " ";
}
}
|
74,494,649
| 74,494,970
|
Coin change problem in C++ stuck on recursion
|
I have to write a recursiive solution to the coin change problem in C++.
The problem provides a set of coins of different values and a value representing a sum to be paid.
The problem asks to provide the number of ways in which the sum can be paid given the coinages at hand.
I am stuck on this:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
long recursive(int amount, vector<long>& input_vector, long ways, vector<long>::const_iterator current) {
if (amount < 0)
return ways;
for (auto iter = current; iter != input_vector.end(); ++iter) {
cout << "amount: " << amount << ", current coin: " << *iter << '\n';
ways += recursive(amount - *iter, input_vector, 0, iter);
cout << "ways: " << ways << '\n';
}
return ways;
}
long getWays(int n, vector<long> c) {
sort(c.begin(), c.end(), greater<long>());
return recursive(n, c, 0, c.begin());
}
int main() {
int amount = 32;
vector<long> coinages = {2, 5, 6, 10};
cout << "Solution is: " << getWays(amount, coinages) << endl;
return 0;
}
The answer should be 27, but I get 0?
Even if I omit the eturn 0 at the end of the main program, I still get 0.
So I'm kind of frustrated my logic does not work here and I'm clueless about how to solve this in a different way.
|
If amount is 0, this is an answer, return 1 to be added to ways. If you got below 0, dead end street, return 0, nothing will be added.
if (amount == 0)
return 1;
if (amount < 0)
return 0;
|
74,494,716
| 74,496,144
|
Std::vector vs. placement new for communicating const array with size known at run-time
|
I have two methods for creating a list of objects at run-time which have potential downsides that I'd like to consider. Ultimately I am wondering which one more e
The criteria of my problem:
One major object will contain a fixed collection of minor objects (technically representing a 2d array)
Desire not to implement default constructor for the minor object since it will have some const paramter that gets assigned via user input (default may lead to invalid states elsewhere in the program!)
Very few (1 for most cases) of the major object will be needed per program execution
The state of each minor object will likely depend on some user input (likely in form of a config file).
My understanding:
Std::vector is likely more clear in how objects are created but I don't want to encourage changing the size of the array which I believe is a somewhat implied feature of any std::vector.
Placement new seems to successfully create pool of objects as desired while discouraging increasing or decreasing the size of the array since there is no default function for this.
I don't see any difference in downstream usage so leaning towards placement new despite the less frequent syntax since it discourages downstream resizing.
Does this reasoning align with the intention of placement new or am I missing a more appropriate standard container?
In the example below object list option 1 & 2 represent a std::vector based approach vs. placement new respectively.
For simplicity I left out any exception handling.
The ideal downstream usage (e.g. no resize) looks the same to me (access via [] operator).
For reference std::vector::emplace vs placement new might seem like a relevant question but I am trying to find an ideal solution for this particular set of criteria where the other question is considerably more vague. It is also possible that a different container or pattern would better solve this and that the two options here are simply a starting point.
#include <vector>
class minorObj{
const int value;
public:
minorObj() = delete;
minorObj(int x):value(x){}
};
class majorObj{
const int N;
public:
std::vector<minorObj> objList_op1;
minorObj* objList_op2;
majorObj(int size):N(size){
objList_op1.reserve(N);
objList_op2 = static_cast<minorObj*>(operator new[](N * sizeof(minorObj)));
for(int i = 0; i<N;i++){
objList_op1.emplace_back(minorObj(i));
new(&objList_op2[i]) minorObj(i);
}
}
~majorObj(){
for(int i = N -1; i >= 0; i--){
objList_op2[i].~minorObj();
}
}
};
void someFn(){majorObj(25);} //added some different scope to emphasize need for proper memory mgmt
int main(){
someFn();
return 0;
}
|
Based on Quentin's comment above an example implementation of a wrapper class could be done with the following template class. This allows for run-time initialization benefits of std::vector while allowing/disallowing other operations as needed. Access to the objects it contains would be the same via the subscript operator.
template <class T>
class RuntimeArray{
private:
std::vector<T> values;
public:
RuntimeArray() = delete;
RuntimeArray(const std::vector<int>& inputs){ // can be whatever type to initialize
values.reserve(inputs.size());
for(int i = 0; i < inputs.size(); i++){
values.emplace_back(inputs[i]);
}
}
T& operator [](int i){
return values[i];
}
const T& operator[](int i) const{
return values[i];
}
// std::vector without std::vector::push_back or std::vector::erase etc.
};
|
74,494,936
| 74,495,466
|
Threadsafe copy constructor
|
I am trying to make the copy constructor of a class thread safe like this:
class Base
{
public:
Base ( Base const & other )
{
std::lock_guard<std::mutex> lock ( other.m_Mutex );
...
}
protected:
std::mutex m_Mutex;
}
class Derived : public Base
{
public:
Derived ( Derived const & other ) : Base ( other )
{
std::lock_guard<std::mutex> lock ( other.m_Mutex );
...
}
}
My problem is that in the derived class I need to lock the mutex before the base class constructor call in the initializer list to guarantee consistency. Any idea how I could achieve that?
Regards.
|
The advice of @AnthonyWilliams is to lock the constructor as an argument of a delegated constructor, see here for the full article:
class A
{
private:
A(const A &a, const std::lock_guard<std::mutex> &)
: i(a.i), i_squared(a.i_squared) {}
public:
A(const A &a) : A(a, std::lock_guard<std::mutex>(a.mtx)) {}
...
};
Note that you lock the other object in order to prevent it being changed by another thread during copy (construction of the object itself is safe). Moreover, the same approach is valid for a move constructor.
An application to your example could look like this (untested & uncompiled):
class Base
{
public:
Base(Base const& other) : Base(other, std::lock_guard<std::mutex>(other.m_Mutex)) {}
virtual ~Base() = default; //virtual destructor!
protected:
Base(Base const& other, std::lock_guard<std::mutex> const&) {}
mutable std::mutex m_Mutex; //should be mutable in order to be lockable from const-ref
};
class Derived : public Base
{
protected:
Derived(Derived const& other, std::lock_guard<std::mutex> const& lock)
: Base(other, lock)
{}
public:
Derived(Derived const& other)
: Derived(other, std::lock_guard<std::mutex>(other.m_Mutex))
{}
};
|
74,495,037
| 74,495,188
|
Does std::unordered_map::erase actually perform dynamic deallocation?
|
It isn't difficult to find information on the big-O time behavior of stl container operations. However, we operate in a hard real-time environment, and I'm having a lot more trouble finding information on their heap memory usage behavior.
In particular I had a developer come to me asking about std::unordered_map. We're allowed to be non-realtime at startup, so he was hoping to perform a .reserve() at startup time. However, he's finding he gets overruns at runtime. The operations he uses are lookups, insertions, and deletions with .erase().
I'm a little worried about that .reserve() actually preventing later runtime memory allocations (I don't really understand the explanation of what it does wrt to heap usage), but .erase() in particular I don't see any guarantee whatsoever that it won't be asking the heap for a dynamic deallocation when called.
So the question is what's the specified heap interactions (if any) for std::unordered_map::erase, and if it actually does deallocations, if there's some kind of trick that can be used to avoid them?
|
The standard doesn't specify container allocation patterns per-se. These are effectively derived from iterator/reference invalidation rules. For example, vector::insert only invalidates all references if the number of elements inserted causes the size of the container to exceed its capacity. Which means reallocation happened.
By contrast, the only operations on unordered_map which invalidates references are those which actually remove that particular element. Even a rehash (which likely allocates memory) does not invalidate references (this is why reserve changes nothing).
This means that each element must be stored separately from the hash table itself. They are individual nodes (which is why it has a node_type extraction interface), and must be able to be allocated and deallocated individually.
So it is reasonable to assume that each insertion or erasure represents at least one allocation/deallocation.
|
74,495,058
| 74,495,078
|
Do WinInet or WinHTTP support custom ports? If so, how do I implement it?
|
I am trying to download a file using both HTTP and HTTPS (in different scenarios) from a service which defaults to using ports 5080 and 5443, respectively. I wanted to use WinInet (or WinHTTP) as they're native to Windows, but it appears that both WinInet and WinHTTP only support using port 80 or port 443, and do not support specifying anything else.
Is it possible to specify a different port, and I've overlooked something? If not, is the next-best native option to drop down to using WinSock?
Edit: As answered below, the third parameter is of type INTERNET_PORT, but will accept any DWORD. Microsoft's documentation is confusing, as written here, InternetConnect, it says "nServerPort can be one of the following values.", which makes one believe only the provided constants are valid.
Instead, you can provide any port value (of type DWORD).
I submitted feedback on the InternetConnect documentation page, so hopefully this will be clearer for future readers.
|
WinInet's InternetConnect() and WinHTTP's WinHttpConnect() both let you specify any port number you want in their respective nServerPort parameters. You don't have to use the pre-defined constants like INTERNET_DEFAULT_HTTP(S)_PORT.
|
74,496,335
| 74,497,162
|
GLSL uint_fast64_t type
|
how can i get an input to the vertex shader of type uint_fast64_t?
there is not such type available in the language how can i pass it differently?
my code is this:
#version 330 core
#define CHUNK_SIZE 16
#define BLOCK_SIZE_X 0.1
#define BLOCK_SIZE_Y 0.1
#define BLOCK_SIZE_Z 0.1
// input vertex and UV coordinates, different for all executions of this shader
layout(location = 0) in uint_fast64_t vertexPosition_modelspace;
layout(location = 1) in vec2 vertexUV;
// Output data ; will be interpolated for each fragment.
out vec2 UV;
// model view projection matrix
uniform mat4 MVP;
int getAxis(uint_fast64_t p, int choice) { // axis: 0=x 1=y 2=z 3=index_x 4=index_z
switch (choice) {
case 0:
return (int)((p>>59 ) & 0xF); //extract the x axis int but i only want 4bits
case 1:
return (int)((p>>23 ) & 0xFF);//extract the y axis int but i only want 8bits
case 2:
return (int)((p>>55 ) & 0xF);//extract the z axis int but i only want 4bits
case 3:
return (int)(p & 0x807FFFFF);//extract the index_x 24bits
case 4:
return (int)((p>>32) & 0x807FFFFF);//extract the index_z 24bits
}
}
void main()
{
// assign vertex position
float x = (getAxis(vertexPosition_modelspace,0) + getAxis(vertexPosition_modelspace,3)*CHUNK_SIZE)*BLOCK_SIZE_X;
float y = getAxis(vertexPosition_modelspace,1)*BLOCK_SIZE_Y;
float z = (getAxis(vertexPosition_modelspace,2) + getAxis(vertexPosition_modelspace,3)*CHUNK_SIZE)*BLOCK_SIZE_Z;
gl_Position = MVP * vec4(x,y,z, 1.0);
// UV of the vertex. No special space for this one.
UV = vertexUV;
}
the error message i am takeing is :
i tried to put uint64_t but the same problem
|
Unextended GLSL for OpenGL does not have the ability to directly use 64-bit integer values. And even the fairly widely supported ARB extension that allows for the use of 64-bit integers within shaders doesn't actually allow you to use them as vertex shader attributes. That requires an NVIDIA extension supported only by... NVIDIA.
However, you can send 32-bit integers, and a 64-bit integer is just two 32-bit integers. You can put 64-bit integers into the buffer and pass them as 2 32-bit unsigned integers in your vertex attribute format:
glVertexAttribIFormat(0, 2, GL_UNSIGNED_INT, <byte_offset>);
Your shader will retrieve them as a uvec2 input:
layout(location = 0) in uvec2 vertexPosition_modelspace;
The x component of the vector will have the first 4 bytes and the y component will store the second 4 bytes. But since "first" and "second" are determined by your CPU's endian, you'll need to know whether your CPU is little endian or big endian to be able to use them. Since most desktop GL implementations are paired with little endian CPUs, we'll assume that is the case.
In this case, vertexPosition_modelspace.x contains the low 4 bytes of the 64-bit integer, and vertexPosition_modelspace.y contains the high 4 bytes.
So your code could be adjusted as follows (with some cleanup):
const vec3 BLOCK_SIZE(0.1, 0.1, 0.1);
//Get the three axes all at once.
uvec3 getAxes(in uvec2 p)
{
return uvec3(
(p.y >> 27) & 0xF),
(p.x >> 23) & 0xFF),
(p.y >> 23) & 0xF)
);
}
//Get the indices
uvec2 getIndices(in uvec2 p)
{
return p & 0x807FFFFF; //Performs component-wise bitwise &
}
void main()
{
uvec3 iPos = getAxes(vertexPosition_modelspace);
uvec2 indices = getIndices(vertexPosition_modelspace);
vec3 pos = vec3(
iPos.x + (indices.x * CHUNK_SIZE),
iPos.y,
iPos.z + (indices.x * CHUNK_SIZE) //You used index 3 in your code, so I used .x here, but I think you meant index 4.
);
pos *= BLOCK_SIZE;
...
}
|
74,496,338
| 74,496,474
|
Can't draw simple bitmap to window in SDL2
|
I'm currently trying to set up a few C++ libraries for a future project. Namely, SDL2.
Here's my code:
#include <iostream>
#include <fstream>
#include <SDL.h>
int SCREEN_WIDTH = 457;
int SCREEN_HEIGHT = 497;
const char* imgpath = "Sprite.bmp";
std::string errmsg;
SDL_Window* window = NULL;
SDL_Surface* screensurface = NULL;
SDL_Surface* image = NULL;
SDL_Rect rect;
struct {
bool wdown;
bool adown;
bool sdown;
bool ddown;
bool edown;
bool escdown;
} kpresses;
void clearkpresses() {
kpresses.wdown = false;
kpresses.adown = false;
kpresses.sdown = false;
kpresses.ddown = false;
kpresses.edown = false;
kpresses.escdown = false;
}
void setrect() {
rect.x = 0;
rect.y = 0;
rect.w = 457;
rect.h = 497;
}
bool gameinit() {
std::ofstream errfile;
errfile.open("errlog.txt");
clearkpresses();
setrect();
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) < 0 ) {
errmsg = "SDL could not initialize! SDL_Error:";
std::cout << errmsg << SDL_GetError() << std::endl;
errfile << errmsg << SDL_GetError() << std::endl;
errfile.std::ofstream::close();
return false;
}
screensurface = SDL_GetWindowSurface(window);
window = SDL_CreateWindow("Transcend", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if( window == NULL ){
errmsg = "Window could not be created! SDL_Error:";
std::cout << errmsg << SDL_GetError() << std::endl;
errfile << errmsg << SDL_GetError() << std::endl;
errfile.std::ofstream::close();
return false;
}
image = SDL_LoadBMP(imgpath);
if (image == NULL) {
errmsg = "Media unable to load! IMG Error: ";
std::cout << errmsg << SDL_GetError() << std::endl;
errfile << errmsg << SDL_GetError() << std::endl;
errfile.std::ofstream::close();
return false;
}
return true;
}
void gamehalt()
{
SDL_DestroyWindow(window);
window = NULL;
SDL_Quit();
}
int main(int argc, char* args[]) {
if (!gameinit()) {
gamehalt();
return 0;
}
bool quit = false;
SDL_Event event;
while (!quit) {
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT) {
quit = true;
}
switch(event.type) {
case SDLK_w:
kpresses.wdown = true;
case SDLK_a:
kpresses.adown = true;
case SDLK_s:
kpresses.sdown = true;
case SDLK_d:
kpresses.ddown = true;
case SDLK_e:
kpresses.edown = true;
case SDLK_ESCAPE:
kpresses.escdown = true;
}
}
//TODOUpdate
//TODORender
SDL_BlitSurface(image, NULL, screensurface, &rect);
SDL_UpdateWindowSurface(window);
//reset
clearkpresses();
}
gamehalt();
return 0;
}
Compiled, assembled, and linked with this windows cmd command:
g++ Main.cpp -static-libgcc -static-libstdc++ -I..\include\SDL2\include\SDL2 -I..\include\SDL2_image\include\SDL2 -L..\include\SDL2\lib -L..\include\SDL2_image\lib -w -lmingw32 -lSDL2main -lSDL2 -o ../Transcend.exe
It compiles and runs with no errors, but only displays a blank screen.
|
The problem is that you are trying to get the window surface, but the window isn't already created.
Please swap those two lines:
screensurface = SDL_GetWindowSurface(window);
window = SDL_CreateWindow("Transcend", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
This way:
window = SDL_CreateWindow("Transcend", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
screensurface = SDL_GetWindowSurface(window);
|
74,496,713
| 74,520,929
|
How to get the type of the values in a C++20 std::ranges range?
|
Given a std::ranges::range in C++20, how can I determine the type of the values in that range?
I want to write a function that makes a std::vector out of an arbitrary range. I'd like this function to have a nice, explicit declaration. Something like:
template<std::ranges::range Range>
std::vector<std::value_type_t<Range>> make_vector(Range const&);
The following seems to work, but the declaration is not explicit and the implementation is ugly (even ignoring that it doesn't allocate the right size up-front where possible).
template<std::ranges::range Range>
auto make_vector(Range const& range)
{
using IteratorType = decltype(std::ranges::begin(std::declval<Range&>()));
using DerefType = decltype(*std::declval<IteratorType>());
using T = std::remove_cvref_t<DerefType>;
std::vector<T> retval;
for (auto const& x: range) {
retval.push_back(x);
}
return retval;
}
Is there a canonical/better/shorter/nicer way to do this?
|
Let's go through this in order:
template<std::ranges::range Range>
auto make_vector(Range const& range)
This is checking if Range is a range, but range isn't a Range, it's a const Range. It's possible that R is a range but R const is not, so you're not actually constraining this function properly.
The correct constraint would be:
template<typename Range>
requires std::ranges::range<Range const>
auto make_vector(Range const& range)
But then that limits you to only const-iterable ranges (which is an unnecessary restriction) and then requires you to very carefully use Range const throughout the body (which is very easy to forget).
Both of which are why, with ranges, you'll want to use forwarding references:
template<std::ranges::range Range>
auto make_vector(Range&& range)
That'll constrain your function properly.
Next:
using IteratorType = decltype(std::ranges::begin(std::declval<Range&>()));
using DerefType = decltype(*std::declval<IteratorType>());
using T = std::remove_cvref_t<DerefType>;
There are type traits for these things directly:
using IteratorType = std::ranges::iterator_t<Range>;
using DerefType = std::iter_reference_t<IteratorType>;
Or:
using DerefType = std::ranges::range_reference_t<Range>;
But also since you want the value type, that's (as already pointed out):
using T = std::ranges::range_value_t<Range>;
Note that the value type is not necessarily just the reference type with the qualifiers removed.
Lastly:
std::vector<T> retval;
for (auto const& x: range) {
retval.push_back(x);
}
return retval;
It'll be more efficient or even more correct to forward the element into push_back (i.e. auto&& x and then FWD(x), instead of auto const& x and x).
Additionally you'll want to, at the very least:
if constexpr (std::ranges::sized_range<Range>) {
retval.reserve(std::ranges::size(range));
}
Since if we have the size readily available, it'll be nice to reduce the allocations to just the one.
Lastly, in C++23, make_vector(r) can just be spelled std::ranges::to<std::vector>(r). This does the allocation optimization I mentioned, but can additionally be more performant since vector's construction internally can avoid the constant checking to see if additional allocation is necessary (which is what push_back has to do).
|
74,497,118
| 74,497,239
|
My stack is not displaying my array but queue display it
|
My Queue is displaying right but my stack is displaying nothing. Im using array to transfer it to stack and to queue but when i transfer the array to stacks and display it, it show nothing. and is there a way to reverse my Queue and save it to my array again?
case 1 is where the input of stack and queue comes, void display in class stack is the problem I copied my whole stack on my stack project where I array transfer to stack but now when I transfer the array to stack and queue, stack gone missing.
class Stack { private:
int MAX;
int top;
int *grd_s;
public:
Stack (int size)
{
MAX=size;
top=-1;
grd_s=new int[MAX];
}
void push(int Q)
{
if ((top+1)==MAX)
cout << "Stack Overflow..." << endl;
top++;
grd_s[top]=Q;
}
void display(int ctr)
{
cout<<"Cloud contains --"<<endl;
for (int ctr=top; ctr>=0; ctr--)
{
if (ctr==top)
cout<<"\t\t"<<grd_s[ctr]<<"<--Top of Stack"<<endl;
else
cout<<"\t\t"<<grd_s[ctr]<<endl;
}
} };
class Queue { private:
int front;
int rear;
int grd_q[5]; public:
Queue()
{
front=-1;
rear=-1;
for (int z=0; z<5; z++)
{
grd_q[z]=0;
}
}
bool isEmpty()
{
if (front==-1||rear==-1)
return true;
else
return false;
}
bool isFull()
{
if (rear==4)
return true;
else
return false;
}
void insert(int val)
{
if(isFull())
{
cout<<"Queue is Full..."<<endl;
return;
}
else if (isEmpty())
{
rear=0;
front=0;
grd_q[rear]=val;
}
else
{
rear++;
grd_q[rear]=val;
}
}
void show()
{
cout<<"Local contains: "<<endl;
for (int x=0; x<5; x++)
{
cout<<grd_q[x]<<" ";
}
}
void rer()
{
cout<<"sad"<<endl;
}
};
case 1:
cout <<"Enter your 5 Grades" << endl;
for (int i=0; i<5; i++)
{
cout << " " << i+1 << " . ";
cin >> grd;
Q[i] = grd;
} system("cls"); break;
|
You need to construct your Stack outside the do-while loop.
As it stands right now, a new Stack is created at each iteration while the previous goes out of scope.
In doing so, you are creating your Stack in the input phase, only for it to get erased at end of the iteration!
Just modify the beginning of your main() function:
int main()
{
Queue q1;
Stack st(5); // Put this line here, outside the loop!
int Q[5];
int choice;
int chc;
int chc2;
int grd;
system("cls");
do
{
// Stack st(5); Not here !
displayRules();
displayRules1();
cin>>choice;
...
|
74,497,274
| 74,497,319
|
How to output Classes and Objects
|
#include <iostream>
using namespace std;
class PrintName{
public:
void studentName(){
cout<<"Name : "<<studentName<<endl;
}
};
class MathClass{
public:
void multiplicationFunc(int x, int y){
cout<<"Result : "<<(x*y)<<endl;
}
};
int main()
{
cout<<endl;
PrintName PN;
PN.studentName("Mark", "Santo");
MathClass MC;
MC.multiplicationFunc(10,5);
}
I am new to C++ and am learning about classes and objects. From what I gathered classes are ways to group functions and objects is the ability to access them? I am having trouble getting this code to work, I receive an error on line 15 for 'error: no match for 'operator<<'. I am trying to fix my class in order for the main function to work. The output should simply be
'Name : Mark Santo'
'Result : 50'
Thank you for your help everyone!
|
It seems like there is no error on line 15. Instead, you did not define the variable studentName in your void studentName() function in line 8. Also, you used 2 arguments for studentName() in line 23, where the original function is not taking any. This is the corrected code:
#include <iostream>
using namespace std;
class PrintName{
public:
void studentName(string x, string y){
cout<<"Name: " << x << " " << y << endl;
}
};
class MathClass{
public:
void multiplicationFunc(int x, int y){
cout<<"Result: " << x*y << endl;
}
};
int main()
{
cout << endl;
PrintName PN;
PN.studentName("Mark", "Santo");
MathClass MC;
MC.multiplicationFunc(10,5);
}
|
74,497,661
| 74,497,745
|
How can I loop through variables by their names?
|
Suppose I have N float variables x0, x1, x2, ..., xn.
I basically want to loop through each of them and sum them all in a final variable sum.
I'm in a context where I cannot make use of data structures like arrays, vectors, etc. If it helps, in my context N is always less than 10.
Is it possible to make a for loop to do this?
My first thought was using macros like the concatenate (##) or something like that but I guess it won't fit my case.
|
not sure whether it fits your needs, but you can try something like:
#define SUM_X0 (x0)
#define SUM_X1 (SUM_X0 + x1)
#define SUM_X2 (SUM_X1 + x2)
#define SUM_X3 (SUM_X2 + x3)
#define SUM_X4 (SUM_X3 + x4)
#define SUM_X5 (SUM_X4 + x5)
#define SUM_X6 (SUM_X5 + x6)
#define SUM_X7 (SUM_X6 + x7)
#define SUM_X8 (SUM_X7 + x8)
#define SUM_X9 (SUM_X8 + x9)
int main(int argc, char* argv[]) {
int x0, x1, x2, x3, x4, x5;
if (scanf("%d %d %d %d %d %d", &x0, &x1, &x2, &x3, &x4, &x5) != 6) {
printf("error");
return 1;
}
printf("%d\n", SUM_X0);
printf("%d\n", SUM_X1);
printf("%d\n", SUM_X2);
printf("%d\n", SUM_X3);
printf("%d\n", SUM_X4);
printf("%d\n", SUM_X5);
return 0;
}
|
74,498,419
| 74,499,236
|
std::bind with std::shared_ptr works on gcc/clang, but not on msvc
|
The following code can be compiled with g++ 8.1.0 and clang 10.0.0.
#include <memory>
#include <iostream>
#include <functional>
int main() {
auto dereference = std::bind(
&std::shared_ptr<int>::operator*,
std::placeholders::_1);
std::shared_ptr<int> sp = std::make_shared<int>(10);
std::cout << dereference(sp) << std::endl;
return 0;
}
However, msvc in vs2022 reports the following error:
example.cpp<source>(6): error C2672: 'std::bind': no matching overloaded function foundC:/data/msvc/14.34.31931-Pre/include\functional(2029): note: could be 'std::_Binder<_Ret,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)'<source>(8):
note: 'std::_Binder<_Ret,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)': could not deduce template argument for '_Ret'<source>(8): note: 'std::_Binder<_Ret,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)': could not deduce template argument for '_Fx'C:/data/msvc/14.34.31931-Pre/include\functional(2024): note: or 'std::_Binder<std::_Unforced,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)'<source>(8): note: 'std::_Binder<std::_Unforced,_Fx,_Types...> std::bind(_Fx &&,_Types &&...)': could not deduce template argument for '_Fx'<source>(11): error C3536: 'dereference': cannot be used before it is initialized<source>(11): error C2064: term does not evaluate to a function taking 1 argumentsCompiler returned: 2
Is it a bug of msvc compiler or the above code can be fixed?
To reproduce the compile error, you can go to https://godbolt.org/ for details.
|
Behavior is unspecified when trying to take the address of a member function of a standard library class. This allows the standard library to choose a different number or different declarations for the overloads of the member function, as long as direct calls still behave as specified by the standard. For example if the implementation chooses to implement operator* with multiple overloads, then taking the address for std::bind won't work since there is no way to deduce which of the overloads you mean.
Instead of std::bind use a lambda that doesn't require taking the address of a function. std::bind is pretty out-dated anyway and lambdas are much simpler to use:
auto dereference = [](auto&& p)->decltype(auto){ return *decltype(p)(p); };
This works for any type and also does perfect-forwarding correctly. If you don't want that you can specify a type explicitly instead of auto and you can replace decltype(p)(p) with p if you don't want perfect-forwarding. You might also want to add a noexcept specification.
->decltype(auto) makes it so that the value category for the function call is also replicated exactly, meaning that if operator* returns a reference, so will the lambda. Without it the lambda will always return by-value. Which one you want depends on the purpose of this callable.
|
74,498,492
| 74,499,587
|
How to efficiently store matmul results into another matrix in Eigen
|
I would like to store multiple matmul results as row vector into another matrix, but my current code seems to take a lot of memory space. Here is my pseudo code:
for (int i = 0; i < C_row; ++i) {
C.row(i) = (A.transpose() * B).reshaped(1, C_col);
}
In this case, C is actually a Map of pre-allocated array declared as Map<Matrix<float, -1, -1, RowMajor>> C(C_array, C_row, C_col);.
Therefore, I expect the calculated matmul results can directly go to memory space of C and do not create temporary copies. In other words, the total memory usage should be the same with or without the above code. But I found that with the above code, the memory usage is increased significantly.
I tried to use C.row(i).noalias() to directly assign results to each row of C, but there is no memory usage difference. How to make this code more efficiently by taking less memory space?
|
The reshaped is the culprit. It cannot be folded into the matrix multiplication so it results in a temporary allocation for the multiplication. Ideally you would need to put it onto the left of the assignment:
C.row(i).reshaped(A.cols(), B.cols()).noalias() = A.transpose() * B;
However, that does not compile. Reshaped doesn't seem to fulfil the required interface. It's a pretty new addition to Eigen, so I'm not overly surprised. You might want to open a feature request on their bug tracker.
Anyway, as a workaround, try this:
Eigen::Map<Eigen::MatrixXd> reshaped(C.row(i).data(), A.cols(), B.cols());
reshaped.noalias() = A.transpose() * B;
|
74,498,531
| 74,499,221
|
C++ - Closure template class behaves strangely when multihreading depending on closure types
|
I am trying to write my own c++ wrapper class for linux using pthreads. The class 'Thread' is supposed to get a generic lambda to run in a different thread and abstract away the required pthread calls for that.
This works fine if the lambdas don't capture anything, however as soon as they capture some shared variables the behaviour seems to become undefined depending on whether or not the template types of two threads are the same or not. If both Thread objects caputre the same types (int and int*) it seems to (probably accidentally) work correctly, however as soon as i pass (e.g. like in my example) an integer A 'aka. stackInt' and an int ptr B 'aka. heapInt' to Thread 1 and only the int ptr B to Thread 2 i get a segfault in Thread 2 while accessing int ptr B.
I know that it must have something to do with the fact that each thread gets its own copy of the stack segment however i cant wrap my head around how that interferes with colsures capturing variables by refernce and calling them. Shouldn't the int ptr B's value point to the same address in each copy of it on the stack? How does the adress get messed up? I really can't wrap my head around whats the exact issue here..
Can anyone help me out here? Thank you in advance.
Here is the full example code:
class 'Thread'
// thread.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
// ******************************* //
// THREAD CLASS //
// ******************************* //
template <typename C>
class Thread
{
private:
C &m_closure;
pthread_t m_thread;
public:
Thread<C>(C &&closure)
: m_closure(closure),
m_thread()
{}
void start()
{
pthread_create(&m_thread, NULL, &Thread::threadFunction, (void *)this);
}
void join()
{
pthread_join(m_thread, NULL);
}
private:
void callbackOnInstance()
{
m_closure();
}
static void * threadFunction(void *);
};
template <typename C>
void * Thread<C>::threadFunction(void *caller)
{
Thread<C> *callerObject = (Thread<C> *)caller;
callerObject->callbackOnInstance();
return nullptr;
}
main() / testing
// main.cpp
// ******************************* //
// TESTING //
// ******************************* //
#define SLEEP_SEC(_sec) usleep((long)(1000 * 1000 * (_sec)))
#include "thread.h"
#include <iostream>
#include <string>
int main(int argc, char **argv)
{
int stackInt = 0;
int *heapInt = new int(0);
// every second each thread increments them, 0.5 s apart from each other
Thread thread1([&]()
{
while(true)
{
SLEEP_SEC(1);
std::cout << "thread #1:" << std::endl;
stackInt += 1;
std::cout << "stack int: " << stackInt << " [" << &stackInt << "]" << std::endl;
*heapInt += 1;
std::cout << "heap int: " << *heapInt << " [" << heapInt << "]" << std::endl;
}
});
thread1.start();
Thread thread2([&]()
{
SLEEP_SEC(0.5);
while(true)
{
SLEEP_SEC(1);
std::cout << "thread #2:" << std::endl;
// if stackInt doesn't get referenced ...
//stackInt += 1;
//std::cout << "stack int: " << stackInt << " [" << &stackInt << "]" << std::endl;
// ... i get a segfault here
*heapInt += 1;
std::cout << "heap int: " << *heapInt << " [" << heapInt << "]" << std::endl;
}
});
thread2.start();
thread1.join();
thread2.join();
}
|
You've got undefined behaviour, since the lambda objects are actually destroyed immediately after the constructor of Thread completes. To see this, instead of a lambda you could pass an object that prints a message in the destructor:
struct ThreadFunctor
{
int& stackInt;
int* heapInt;
ThreadFunctor(int& si, int* hi)
: stackInt(si),
heapInt(hi)
{
std::cout << "ThreadFunctor created: " << this << '\n';
}
~ThreadFunctor()
{
std::cout << "ThreadFunctor destroyed: " << this << '\n';
}
void operator()() const
{
using namespace std::chrono_literals;
while (true)
{
std::this_thread::sleep_for(1s);
std::cout << "thread #1:" << std::endl;
stackInt += 1;
std::cout << "stack int: " << stackInt << " [" << &stackInt << "]" << std::endl;
*heapInt += 1;
std::cout << "heap int: " << *heapInt << " [" << heapInt << "]" << std::endl;
}
}
};
Thread thread1(ThreadFunctor{stackInt, heapInt});
std::cout << "before start\n";
thread1.start();
The following output is guaranteed for every standard compliant C++ compiler (modulo addresses):
ThreadFunctor destroyed: 0000006E3ED6F6F0
before start
...
Furthermore the join operation only completes after the operation on the background thread has been completed, so because of the infinite loops your program won't terminate. You need some way of notifying the background threads to actually return instead of continuing forever.
Note that the standard library already contains the exact logic you're trying to implement here: std::thread or std::jthread for a implementation with builtin way of informing the background thread of a termination request.
int main()
{
using namespace std::chrono_literals;
int stackInt = 0;
int* heapInt = new int(0);
// every second each thread increments them, 0.5 s apart from each other
std::jthread thread1{ [=](std::stop_token stopToken, int& stackInt)
{
using namespace std::chrono_literals;
while (!stopToken.stop_requested())
{
std::this_thread::sleep_for(1s);
std::cout << "thread #1:" << std::endl;
stackInt += 1;
std::cout << "stack int: " << stackInt << " [" << &stackInt << "]" << std::endl;
*heapInt += 1;
std::cout << "heap int: " << *heapInt << " [" << heapInt << "]" << std::endl;
}
}, std::ref(stackInt) }; // thread started immediately
std::this_thread::sleep_for(10s);
thread1.request_stop();
thread1.join();
}
|
74,498,709
| 74,499,224
|
C++\C | Link | Queue | Hyperlink
|
when i choose at Queue insert value ( example 1 ), then i call remove_Queue, and then i try to print_Queue, but in terminal i see value -572662307
code:
const int MAX_QUEUE = 10;
typedef int Item;
struct Queue {
Item value;
Queue* next;
};
Queue* front;
Queue* back;
Queue* tmp;
bool remove_Queue(Item& i,Queue* front, Queue* back)
{
if (front == NULL) return false;
i = front->value;
Queue* tmp = front;
front = front->next;
delete tmp;
if (x == 0) back = NULL // x-- in main, when i call this function
return true;
}
I hope someone can explain why i see this value when i delete just 1 value in my Queeu
|
You have global variables (that's bad), and you have local variables named the same as your global variables (that's worse) and you are expecting changes to local variables to be reflected outside of the local scope (that's plain wrong).
It's not completely clear what you are trying to do. I'm going to go down the global variable route (which is bad as I said above, but perhaps easier to understand).
I'm going to use the global variables as global variables, this means removing them as parameters to your remove_Queue function, but I'm going to change tmp to a local variable, which is what it should be.
const int MAX_QUEUE = 10;
typedef int Item;
struct Queue {
Item value;
Queue* next;
};
Queue* front;
Queue* back;
As you can see tmp has gone.
bool remove_Queue(Item& i)
{
if (front == NULL)
return false;
i = front->value;
Queue* tmp = front;
front = front->next;
delete tmp;
if (front == NULL) // is the queue empty?
back = NULL;
return true;
}
As you can see front and back are no longer parameters, so changes to them will affect the global variables declared above, instead of the local variables you had before. I also simplified this function, removing the parts I didn't understand. I also added a check for an empty queue, presumably then back should also be set to NULL.
|
74,498,900
| 74,498,923
|
Why does the data still exist after I delete the space of the array?
|
Today, I found a small problem when creating dynamic arrays.
I use the resize () function to change the size of the array. In the resize () function, I created a temporary array "newData", and then I assigned it the new size I wanted. After assigning the value of the initial array "Data" to it, I set
Data=newData;
At this time, the task of the resize () function has been completed. Before exiting the function, I had a whim and deleted the space of "newData" by
delete [] newData;
After that, when I output the value of Data [2], I can still output the value.
Now I'm a little confused. "Data" and "newData" should be pointers, right? When I use the statement "Data=newData;", what "Data" points to should become the address space that "newData" points to. If I delete the address space of "newData", shouldn't the space corresponding to "Data" also disappear? Why can I continue to output values?
The following is the complete code
#include<iostream>
using namespace std;
int Length = 0;
int* Data;
void resize(int,int *);
int main()
{
Data = new int[5];//This is the space I allocated for the initial array
for (int i = 0; i < 5; i++)
Data[i] = i;
Length = 5;//There are five data in the initial array
int newLength = 10;//I started distributing new sizes to the initial array
resize(newLength,Data);
cout << Data[2];//The output is still 2
}
void resize(int newLength,int *Data)
{
int* newData = new int[newLength];//A temporary array
for (int i = 0; i <Length; i++)//Move the value of the original array to the temporary array
{
newData[i] = Data[i];
}
Data = newData;
delete[] newData;//Delete the space where the temporary array is located
}
|
You (try to¹) access deleted space; that's what is called undefined behaviour in C++: Anything might happen. There might be the original values, the might be some other data you worked on put there, there might be the value 0xdeadcafe all over the place, your program might crash or cause a fire, delete all files or give an attacker access.
It's undefined, and you found one of the things that might happen.
¹ From your question, that was your intent. Luckily, you messed up your resize function prototype, and pass in the Data pointer by value, not by reference, so that your Data = newData; doesn't do anything outside your function. That together with the global variables on top of your files: Maybe revisit what a function is and what scope and pass-by-reference mean!
Generally, you're a C++ beginner: cool! That's a good path to be on.
Maybe do less with new and delete. It's been a while since I used these two, they're becoming a rare pattern in modern C++! C++ can very well (for the most part) be written without these, completely, by using other methods, where your memory allocation and deallocation are linked to objects' lifetimes. And that's way less error-prone, and honestly, easier to understand.
For example, in your use case, instead of your Data, newData, new and delete handling, you could have said std::vector<int> Data(Length);, have put the values in exactly as you did, and then just called Data.resize(newLength);. No need for manually knowing where to delete your memory!
I'm not sure why you're doing this, but you're declaring your variables globally. That's a bad idea from start to finish, so, um, just don't do that: Declare variables in the scope you need them, which would be your main function. Maybe someone who has had a very early 1970's copy of some C book confused obsolete C with the C++ you should be taught? I don't know. Global variables are generally a bad idea.
|
74,499,887
| 74,499,974
|
Why doesn't this code for a binary search function in c++ work?
|
#include <iostream>
int binary_search(int arr[], int size, int target)
{
int first = 0;
int last = size - 1;
int midpoint = (last + first) / 2;
while(first <= last)
{
if(arr[midpoint] == target)
{
return midpoint;
}
else if(arr[midpoint] < target)
{
first = midpoint + 1;
}
else if(arr[midpoint] > target)
{
last = midpoint - 1;
}
}
return 0;
}
int main()
{
int arr[] = {4, 12, 23, 43, 50, 60, 230, 290};
int size = sizeof(arr)/sizeof(arr[0]);
int target = 12;
std::cout << binary_search(arr, size, target);
}
if the midpoint value is lesser than the target it increases 'first' and if it's greater than the target it instead decreases 'last'. This continues until 'first' is equal to 'last'.
I saw another program where they called the function recursively but i wanted to make it work without it, what exactly am i doing wrong?
|
You basically forgot to update midpoint in each iteration.
An updated version of your code here (not using those "C" style arrays).It was also not clear if you meant to return the found value or the index at which it was found.
#include <iostream>
#include <vector>
auto binary_search(const std::vector<int>& values, int value)
{
std::size_t first = 0;
std::size_t last = values.size() - 1; // use vector it keeps track of its size
while (first <= last)
{
std::size_t midpoint = (last + first) / 2; // you forgot to update midpoint each loop
if (values[midpoint] == value)
{
return values[midpoint]; // <== do you want to return the position or the value?
}
if (values[midpoint] < value)
{
first = midpoint + 1;
}
else if (values[midpoint] > value)
{
last = midpoint - 1;
}
}
return 0;
}
int main()
{
std::vector<int> values{ 4, 12, 23, 43, 50, 60, 230, 290 };
std::cout << binary_search(values, 12);
return 0;
}
|
74,500,509
| 74,500,510
|
"Failed to setup resampler" when starting QAudioSink
|
I'm porting some QtMultimedia code from Qt 5.15 to 6.4.1. The following program, when built with Qt 6.4.1 on Windows:
int main (int argc, char *argv[]) {
QCoreApplication a(argc, argv);
QAudioDevice device = QMediaDevices::defaultAudioOutput();
QAudioFormat format = device.preferredFormat();
QAudioSink *output = new QAudioSink(device, format);
output->start();
return a.exec();
}
Fails to start the audio output, printing the following message:
qt.multimedia.audiooutput: Failed to setup resampler
The equivalent code in Qt5 (using QAudioDeviceInfo and QAudioOutput) seems to run fine. What am I missing here?
|
Apparently, it's a bug in Qt 6.4.1 on Windows, where, as the user johnco3 discovered in that forum post, for some reason QAudioSink is looking for a DLL named "mfplat.dll.dll" when it should be looking for "mfplat.dll" (it adds an extra ".dll" suffix).
The correctly named version of this DLL lives in the Windows system directory (e.g. C:\Windows\System32\mfplat.dll), so there are a couple of workaround until the bug is fixed:
Go back to Qt 6.4.0, apparently it's a new issue in 6.4.1, or
Copy mfplat.dll to somewhere in the DLL path then rename it to "mfplat.dll.dll":
Either copy it to the application executable's directory and rename it there, or
Create some folder somewhere, copy and rename it there, then add that folder to the PATH environment variable.
It's a somewhat silly bug, but alas. At least the workaround exists and can be easily undone when the bug is eventually fixed.
See also:
https://bugreports.qt.io/browse/QTBUG-108383 (johnco3's bug report)
https://bugreports.qt.io/browse/QTBUG-108669 (a duplicate bug report; I filed it before I found any of this)
|
74,500,555
| 74,500,602
|
I found this question, but I can't code it. [TODO list]
|
Aman has made a To-Do list: a list of all the pending tasks that he has to complete. The list is in the increasing order of time taken to finish the tasks. Aman begins from the starting of the list.
Given an array of size N denoting the list of the pending tasks. Each task is an integer between 1 and N. The tasks numbered from 1 to 7 are classified as top priority tasks. Aman needs to know the minimum number of tasks he has to complete in order to get all the top priority tasks accomplished. Can you help him to do so?
Two Samples are given as if input array is
1 5 2 4 9 3 6 7 8
Output is
8
And,
10 9 8 7 6 5 4 3 2 1
Output is
10
I could only code till counting for all 1 to 7 exist, here's what I coded
#include <iostream>
using namespace std;
int main()
{
int n, count = 0;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n; i++)
{
if (arr[i] <= 7)
{
count++;
}
}
cout << count << endl;
return 0;
}
I understood the logic behind the question, but I can't put it into code, like what should I do to count for minimum tasks, in second sample 10 9 8 came before all "important tasks" so he needs to do them till he gets to 1-7, and in first 8th came at last but 1-7 including 9 was done so minimum was 8.
|
Something like this, loop though the tasks counting the priority ones. When the number of priority tasks reaches 7, stop the loop and print out the number of tasks seen so far.
int tasks = 0, pri_tasks = 0;
for (; tasks < n && pri_tasks < 7; tasks++)
{
if (arr[tasks] <= 7)
++pri_tasks;
}
if (pri_tasks == 7)
cout << tasks << '\n';
|
74,500,928
| 74,501,076
|
How to count string and sort them?
|
I am reading from an input file and want to read all letters and symbols. I am looking to create something bigger from this like encode it eventually - but I cannot seem to move from this block of trying to read in characters and use its frequency in a vector which I would sport in a heap. For context, how can I get something like this:
"I am soo stuck." --> i:1 a:1 m:1 s:2 o:2 t: 1 u:1 c: 1 k:1 :3 (represents spacing)
-- and how can i order them from least to greatest frequencies?
I tried maps, vectors, pairs -- everything - but no matter what i try nothing works
|
The most straightforward way would be to first create a std::map for the frequencies (similar to your dictionary map, but you need to use a std::(unordered)_map<char, int> instead of <int,char>). Then you can use a std::multimap where you insert the all reverse pairs.
#include <iostream>
#include <map>
#include <string>
void print_frequencies(std::string text) {
std::map<char, int> dictionary;
for(auto c: text) {
dictionary[c]++;
}
std::multimap<int, char> reverse;
for ( auto [c, i] : dictionary ) {
reverse.emplace(i, c);
}
for ( auto [i, c] : reverse ) {
std::cout << c << ':' << i << '\n';
}
}
int main() {
print_frequencies("I am soo stuck.");
}
This works because std::multimap stores its elements in order of the key. You can play with it live on the godbolt compiler explorer.
If you only happen to have a pre C++17 compiler you cannot use structured bindings and need to use old school std::pair members. For example the second loop would look like this in C++14:
for ( auto e : dictionary ) {
reverse.emplace(e.second, e.first);
}
|
74,501,189
| 74,501,542
|
trouble understanding list.begin() | list.end() | list<int>::iterator i
|
void Graph::max_path(){
for(int i=0; i <N; i++){
cost[i]=0; cam_max[i]=999;
}
// Percorre todos os vertices adjacentes do vertice
int max = 0;
list<int>::iterator i;
for (int a = 0; a < N ; a++){
int v = ordely[a];
for (i = adj[v].begin(); i != adj[v].end(); ++i){
int viz = *i;
if (cost[viz]<cost[v]+1){
cost[viz] = cost[v]+1;
if(cost[viz]>max) max = cost[viz];
}
}
}
cout << "\nCusto maximo " << max;
}
I need to convert this C++ program to a python program... However, I'm struggling to understand what this adj[v].begin() inside the for loop means. Can anyone explain it to me, please?
|
begin and end are iterators (specfically, pointers), which are used to iterate over a container.
You could imagine begin as 0 and end as the size of an array. So it is like for (i = 0; i < size; ++i).
However, the thing about pointers is that they're addresses, so in C++, i < end (where i started as begin) is more like 0xF550 < 0xF556 (example) which has the same effect of iterating 6 times assuming i increases each iteration.
In fact, that's actually how for-each loops work behind the scenes in many languages.
In python, just use a normal for-loop.
I don't know much about python or your Graph class but I guess this could get you started:
def max_path(self) :
for i in range(N) :
self.cost[i] = 0
self.cam_max[i] = 999
max = 0
for a in range(N) :
v = self.ordely[a]
for i in self.adj[v] :
viz = i
if self.cost[viz] < self.cost[v] + 1 :
self.cost[viz] = self.cost[v] + 1
if self.cost[viz] > max :
max = self.cost[viz]
print("\nCusto maximo ", max)
Notice how iterators weren't needed in the python version cause you used a normal for-loop.
By the way, in C++, you could use for/for-each too, the code you posted is unnecessarily complicated and unoptimized. For example, the first 2 loops in your code could be merged into 1 loop cause they both had the exact same range thus I optimized them into 1.
|
74,501,884
| 74,502,008
|
LibTorch (PyTorch C++) LNK2001 errors
|
I was following the tutorial in LibTorch here.
With the following changes:
example-app => Ceres
example-app.cpp => main.cxx
Everything worked until the CMake command cmake --build . --config Release.
It produced the following errors:
main.obj : error LNK2001: unresolved external symbol __imp___tls_index_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA [D:\Silverous Black\CPE42S2-CPE42S2\CPE 406\ProjectDumagan\src\Ceres\build\Ceres.vcxproj]
main.obj : error LNK2001: unresolved external symbol __imp___tls_offset_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA [D:\Silverous Black\CPE42S2-CPE42S2\CPE 406\ProjectDumagan\src\Ceres\build\Ceres.vcxproj]
D:\Silverous Black\CPE42S2-CPE42S2\CPE 406\ProjectDumagan\src\Ceres\build\Release\Ceres.exe : fatal error LNK1120: 2 unresolved externals [D:\Silverous Black\CPE42S2-CPE42S2\CPE 406\ProjectDumagan\src\Ceres\build\Ceres.vcxproj]
I don't believe these are from the changes I placed, since the problem is with the linking.
I also am trying to replicate this directly into Visual Studio. I am using Visual Studio 17 2022 which the LibTorch extension is not yet compatible with (Visual Studio 16 2019 is no longer available for install from the website).
The replication is through a blank C++ template (no starting files). And I have set the following macros:
LibTorchTarget = CPU specifies libtorch for CPU is to be used (useful for other macros
LibTorchDir = C:/libtorch/ directory where the libtorch installation(s) can be found (for multiple installations)
LibTorchInstall = $(LibTorchDir)libtorch_$(LibTorchTarget)/ expresses to C:/libtorch/libtorch_CPU/
LibTorchInclude = $(LibTorchInstall)include/ expresses to C:/libtorch/libtorch_CPU/include/
LibTorchLib = $(LibTorchInstall)lib/ expresses to C:/libtorch/libtorch_CPU/lib/
And have put the Include and Lib macros at their respective VC++ Directories positions. As well as $(LibTorchLib)*.lib (C:/libtorch/libtorch_CPU/lib/*.lib) in the Linker > Input > Additional Dependencies to specify all the .libs for linking (prevents a lot of LNK2009 errors).
And lastly, I have put start xcopy /s "$(LibTorchLib)*.dll" "$(OutDir)" /Y /E /D /R command at the Build Events > Pre-Link Event > Command Line to replicate the if clause in the CMakeLists.txt in the tutorial (apparently to avoid memory errors).
Result is same exact error with a final LNK1120 error:
Error LNK2001 unresolved external symbol __imp___tls_index_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA Ceres D:\Silverous Black\CPE42S2-CPE42S2\CPE 406\ProjectDumagan\src\Ceres\main.obj 1
Error LNK2001 unresolved external symbol __imp___tls_offset_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA Ceres D:\Silverous Black\CPE42S2-CPE42S2\CPE 406\ProjectDumagan\src\Ceres\main.obj 1
Error LNK1120 2 unresolved externals Ceres D:\Silverous Black\CPE42S2-CPE42S2\CPE 406\ProjectDumagan\out\Debug_64\Ceres\Ceres.exe 1
I don't exactly understand the reason for the LNK errors, so if anyone could help that'll be really nice. Thank you in advance.
|
Look to: Updating to Visual Studio 17.4.0 Yields linker errors related to TLS
You most likely need to rebuild PyTorch after MSVC update.
|
74,502,062
| 74,503,892
|
Unabled to load lohmann/json.hpp using CMake - getting fatal error: 'nlohmann/json.hpp' file not found
|
I have the following main.cpp, very simple script, trying to re-produce the problem and isolate to it's most basic.
#include<iostream>
#include<fmt/core.h>
// #include "json/json.hpp"
// #include <json/json.hpp>
// #include <nlohmann/json.hpp>
// #include "json.hpp"
// #include "nlohmann/json.hpp"
int main(){
fmt::print("Hello, world!\n");
return 0;
}
The commented out include statements are all of the paths I have tried to get this into my program.
My CMakeLists.txt file looks like this
cmake_minimum_required(VERSION 3.24)
project(main)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-std=c++17")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/build)
# include(FetchContent)
# FetchContent_Declare(
# json
# GIT_REPOSITORY https://github.com/nlohmann/json
# )
# FetchContent_MakeAvailable(json)
include(FetchContent)
FetchContent_Declare(fmt
GIT_REPOSITORY https://github.com/fmtlib/fmt
GIT_TAG 9.0.0
)
FetchContent_MakeAvailable(fmt)
add_executable(main main.cpp)
# target_link_libraries(main json)
target_link_libraries(main fmt)
I've commented out the json part since it's not working obviously, I can also json-src and json-build in my _deps folder so I know for a fact that it is being downloaded into my local machine.
After running cmake CMakeLists.txt and make and then running the executable I get the error in the title 'nlohmann/json.hpp' file not found
Any help would be appreciated.
Tried to reproduce the example with another popular C++ package which worked fine. Tried changing the include statements to see if maybe I had something wrong since I don't fully understand all the nuance with CMake and am quite new to it.
|
You can either specifically use the interface target already included in the nlohmann library, which will automatically populate the correct include path for you, with:
target_link_libraries(main nlohmann_json::nlohmann_json)
Or you would need to specifically include the include path yourself:
include_directories(${json_SOURCE_DIR}/include)
With either way, you will be able to use #include <nlohmann/json.hpp> in your source.
|
74,502,063
| 74,515,844
|
yaml-cpp doesn't roundtrip with local tags
|
When I YAML::Load a node with a local tag, the tag type and tag contents are not preserved.
Minimal example
I am using the 0.7.0 conan package.
auto x = YAML::Node(42);
YAML::Emitter e;
e << YAML::LocalTag("x") << x;
std::string s = e.c_str();
auto y = YAML::Load(s);
std::cout << "before: " << s << std::endl;
std::cout << "tag: " << y.Tag() << std::endl;
std::cout << "after: " << YAML::Dump(y) << std::endl;
prints
before: !x 42
tag: !x
after: !<!x> 42
Expected:
before: !x 42
tag: x
after: !x 42
I suppose two things are going wrong here:
The leading exclamation mark is added to the tag contents
The tag type changes from _Tag::Type::PrimaryHandle to _Tag::Type::Verbatim
So I have two questions:
Is this a bug or am I doing it wrong? I am not 100% sure I correctly understand the complicated yaml specs for tags...
Is there any way to set the _Tag::Type for an existing node as a workaround?
Note: I already posted this question as a Github issue. Please excuse the redundancy.
|
Your problem is this code:
void EmitFromEvents::EmitProps(const std::string& tag, anchor_t anchor) {
if (!tag.empty() && tag != "?" && tag != "!")
m_emitter << VerbatimTag(tag);
if (anchor)
m_emitter << Anchor(ToString(anchor));
}
The primary problem is that the default emitter always produces verbatim tags. The secondary problem is that the node doesn't remember the tag style.
To answer the question is this a bug: No. The YAML spec does not guarantee any form of round-tripping. An implementation is allowed to emit YAML in any style it wants as long as the output's semantics are correct.
To answer the question of whether a workaround is possible: Not with the existing emitter – as you can see, there's no settable option that modifies this behavior. You could theoretically write an own emitter that handles this to your liking; I am not entirely sure whether the API gives you enough access to internals to easily adapt the existing emitter.
In any case, that would be too involved for a SO answer.
|
74,502,473
| 74,504,400
|
How can I make a function use the child object associated function instead of the parent one?
|
I'm coding a simple physics engine with a few others for a school assignment. In order to be as generic, we made a Particle class, then an Object class which inherits it (and is basically a particle with a force vector), and finally a Disc class which is a child class of Object.
In my class PyhsicsWorld, I want to use a list of Objects and iterate on it to resolve collisions. For that, I declared the intersects(Object o1, Object o2) and GetPenDist(Object o1, Object o2) functions, but they aren't supposed to be called. Instead, I'm overloading these functions in Disc and I want the program to use these instead.
I only create and use Discs (for now), so I'm sure there isn't any reason (other than me not understanding my code) for the program to call intersects on Objects instead of Disc. Here is my code :
Object.h :
#include <iostream>
#include "./Particle.h"
class Object : public Particle {
//Some code
};
bool intersects(Object o1, Object o2);
float getPenDist(Object o1, Object o2);
Object.cpp :
#include "./Object.h"
bool intersects(Object o1, Object o2) {
std::cout << "Bad Intersects" << std::endl;
return false;
}
float getPenDist(Object o1, Object o2) {
std::cout << "Bad PenDist" << std::endl;
return 0;
}
Disc.h :
#include "./Object.h"
class Disc : public Object {
protected :
float radius;
public :
float getRadius() { return radius; }
//Some code
};
bool intersects(Disc d1, Disc d2);
float getPenDist(Disc d1, Disc d2);
Disc.cpp :
#include "./Disc.h"
bool intersects(Disc d1, Disc d2) {
return (d2.getPosition() - d1.getPosition()).getNorm() < d1.getRadius() + d2.getRadius();
}
float getPenDist(Disc d1, Disc d2) {
return -(d2.getPosition() - d1.getPosition()).getNorm() - d1.getRadius() - d2.getRadius();
}
PhysicsWorld.h :
class PhysicsWorld {
protected:
std::vector<Object*> objectList;
void resolveCollisions(float duration);
};
PhysicsWorld.cpp :
#include "PhysicsWorld.h"
void PhysicsWorld::resolveCollisions(float duration) {
std::vector<Object*>::iterator iter, iter2;
for (iter = objectList.begin(); iter != objectList.end(); ++iter) {
for (iter2 = objectList.begin(); iter2 != objectList.end(); ++iter2) {
if (!(*iter == *iter2))
{
if (intersects(**iter, **iter2))
{
//Do something
}
}
}
}
}
My problem here is that the code is running the Intersects(Object*, Object*) function in the resolveCollisions method while I'd like it to run the Intersects(Disc*, Disc*) function.
Please note that these classes are heavily simplified to only include relevant code.
Furthermore, while I'd love to make Object::Intersects(Object o), I can't do that as I can't override it afterward with Disc::Intersects(Disc d).
Thank you very much for any help you can provide !
|
If you really need to call for Disc, just cast it. I further assume that you need general solution for multiple shapes, like Disc, Cube, Sphere etc.
So I prepared example for you, that is based on virtual functions and shows how can you choose correct function for Disc and Cube.
class Disc;
class Cube;
bool intersectDiscVsDisc(Disc*, Disc*);
bool intersectCubeVsDisc(Cube*, Disc*);
bool intersectCubeVsCube(Cube*, Cube*);
class Object {
public:
virtual bool intersects(Object *) = 0;
virtual bool intersectsVsDisk(Disc *) = 0;
virtual bool intersectsVsCube(Cube *) = 0;
};
class Disc : public Object {
virtual bool intersects(Object * another) override
{ return another->intersectsVsDisk(this); }
virtual bool intersectsVsDisk(Disc * another)
{ return intersectDiscVsDisc(this, another); }
virtual bool intersectsVsCube(Cube * another)
{ return intersectCubeVsDisc(another, this); }
};
class Cube : public Object {
virtual bool intersects(Object * another) override
{ return another->intersectsVsCube(this); }
virtual bool intersectsVsDisk(Disc *another)
{return intersectCubeVsDisc(this, another); }
virtual bool intersectsVsCube(Cube *another)
{ return intersectCubeVsCube(this, another); }
};
|
74,502,731
| 74,502,812
|
Disabling a constructor using std::enable_if
|
My aim is to create my own analogue of std::basic_string but with some additional conditions. I want my AnyString<CharType, Traits> to be convertible from std::basic_string<CharType, AnyOtherTraits, AnyAlloc> but I want to disable this constructor for some CharType such that basic_string<CharType> does not exist (compile).
I tried to do something like that:
template<typename OtherTraits, typename Alloc, typename =
std::enable_if_t<!std::is_array_v<char_type> &&
std::is_trivial_v<char_type> &&
std::is_standard_layout_v<char_type>>>
AnyString(const std::basic_string<char_type, OtherTraits, Alloc>&);
And I have ColouredChar, which does not meet the conditions listed inside enable_if_t.
Now, when I'm trying to call the disabled constructor :
std::basic_string<ColouredChar> de("string"_purple);
ColouredString d(de);
I do not only get the compile errors from basic_string but also very strange one, telling me that completely different PRIVATE constructor constructor cannot convert its parameter from basic_string.
Is there any way to make these compile errors more readable? Or at least explain whether there's anything here to worry about.
|
Basic example for constructor restriction using concepts (not your traits)
#include <type_traits>
#include <string>
// declare your own concept
template<typename type_t>
concept my_concept = std::is_convertible_v<type_t, std::string>; // just a demo concept
class ColouredString
{
public:
// then you can limit your constructor to types satisfying that concept
ColouredString(const my_concept auto& /*arg*/)
{
}
~ColouredString() = default;
};
int main()
{
// ColouredString str{ 1 };
ColouredString str{ "hello world!" };
return 0;
}
|
74,503,028
| 74,640,899
|
Compiling out strings used in print statements in multi-level log - C++
|
I'm looking for a way to compile print strings out of my binary if a specific macro-based condition is met.
here, _dLvl can be conditionally set equal or lower than the maximum allowed level.
enum DEBUG_LEVELS : int
{
DEBUG_NONE,
DEBUG_ERRORS,
DEBUG_WARN,
DEBUG_INFO,
DEBUG_VERBOSE
};
#define MAX_LEVEL DEBUG_WARN
int _dLvl = DEBUG_ERRORS;
template <typename... Args> void E(const char * _f, Args... args){
if (_dLvl >= DEBUG_ERRORS){
printf(_f, args...);
}
}
template <typename... Args> void W(const char * _f, Args... args){
if (_dLvl >= DEBUG_WARN){
printf(_f, args...);
}
}
template <typename... Args> void I(const char * _f, Args... args){
if (_dLvl >= DEBUG_INFO){
printf(_f, args...);
}
}
template <typename... Args> void V(const char * _f, Args... args){
if (_dLvl >= DEBUG_VERBOSE){
printf(_f, args...);
}
}
int main(){
E("This will print\n");
W("This might be printed based on _dLvl, existence of this string is ok.\n");
I("This wont print ever, the existence of this string is memory waste\n");
V("Same as I\n");
}
What adds to the challenge that I've multiple instances of a logger class, where each instance would have a different MAX level, see this question for a more clear example of multi-instances.
Here's a solution for my situation (but an ugly and unmanageable onewherein it requires a special macro per instance to be used differently within the source code):
#if (WIFI_LOG_MAX_LEVEL >= 1)
#define w_log_E(f_, ...) logger.E((f_), ##__VA_ARGS__)
#else
#define w_log_E(f_, ...)
#endif
#if (WIFI_LOG_MAX_LEVEL >= 2)
#define w_log_W(f_, ...) logger.W((f_), ##__VA_ARGS__)
#else
#define w_log_W(f_, ...)
#endif
#if (WIFI_LOG_MAX_LEVEL >= 3)
#define w_log_I(f_, ...) logger.I((f_), ##__VA_ARGS__)
#else
#define w_log_I(f_, ...)
#endif
#if (WIFI_LOG_MAX_LEVEL >= 4)
#define w_log_V(f_, ...) logger.V((f_), ##__VA_ARGS__)
#else
#define w_log_V(f_, ...)
#endif
Is there any trick to solve it?
|
Here's a complete answer, it's based on Nikos Athanasiou's answer (Thanks Nikos).
What's added is a templated class per DEBUG_LEVELS enum, which defines the MAX_LEVEL, which would be used in constexpr if statement at compile time, to compile out unused strings.
#include <utility>
#include <cstdio>
enum DEBUG_LEVELS : int
{
DEBUG_NONE,
DEBUG_ERRORS,
DEBUG_WARN,
DEBUG_INFO,
DEBUG_VERBOSE
};
template <int MAX_LEVEL>
class Logger {
DEBUG_LEVELS dLvl;
public:
void set_level(DEBUG_LEVELS level) {
if (level > MAX_LEVEL)
dLvl = static_cast<DEBUG_LEVELS>(MAX_LEVEL);
else
dLvl = level;
}
Logger(DEBUG_LEVELS defaultLvl) {
if (defaultLvl > MAX_LEVEL)
dLvl = static_cast<DEBUG_LEVELS>(MAX_LEVEL);
else
dLvl = defaultLvl;
}
template <class... Args>
void warning([[maybe_unused]] const char *msg, Args&&... args)
{
if constexpr (MAX_LEVEL >= DEBUG_WARN) {
if (dLvl >= DEBUG_WARN)
printf(msg, std::forward<Args>(args)...);
}
}
template <class... Args>
void info([[maybe_unused]] const char *msg, Args&&... args)
{
if constexpr (MAX_LEVEL >= DEBUG_INFO) {
if (dLvl >= DEBUG_INFO)
printf(msg, std::forward<Args>(args)...);
}
}
};
Logger<DEBUG_WARN> logger(DEBUG_WARN);
Logger<DEBUG_INFO> logger_2(DEBUG_INFO);
int main()
{
logger.warning("Ruuuun %i\n", 2);
logger.info("Fuuuun %i\n", 2);
logger_2.info("Hello\n");
logger_2.set_level(DEBUG_NONE);
logger_2.info("Doesn't print\n"); // Dynamically set (But the whole call and related string are optimised by the compiler..)
}
|
74,503,659
| 74,503,748
|
How to calculate the total distance between various vertices in a graph?
|
Let's say I have a weighted, undirected, acyclic graph with no negative value weights, comprised of n vertices and n-1 edges. If I want to calculate the total distance between every single one of them (using edge weight) and then add it up, which algorithm should I use? If for example a graph has 4 vertices, connected like a-b, a-c, c-d then the program should output the total distance needed to go from a-d, a-c, a-b, b-c, b-d and so on. You could call it every possible path between the given vertices. The language I am using is C++.
I have tried using Dijikstra's and Prim's algorithm, but none have worked for me. I have thought about using normal or multisource DFS, but I have been struggling with it for some time now. Is there really a fast way to calculate it, or have I misunderstood the problem entirely?
|
Since you have an acyclic graph, there is only one possible path between any two points. This makes things a lot simpler to compute and you don't need to use any real pathfinding algorithms.
Let's say we have an edge E that connects nodes A and B. Calculate how many nodes can be reached from node A, not using edge E (including A). Multiply that by the number of nodes that can be reached from node B, not using edge E (including B). Now you have the number of paths that travel through edge E. Multiply this by the weight of edge E, and you have the total contribution of edge E to the sum.
Do the same thing for every edge and add up the results.
To make the algorithm more efficient, each edge can store cached values that say the number of nodes that are reachable on each side of the edge.
You don't have to use a depth first search. Here is some pseudocode showing how you calculate the number of nodes reachable on a side of edge E very fast taking advantage of caching:
int count_nodes_reachable_on_edge_side(Edge e, Node a) {
// assume edge e directly connects to node a
if (answer is already cached in e) { return the answer; }
answer = 1; // a is reachable
for each edge f connected to node a {
if (f is not e) {
let b be other node f touches (not a)
answer += count_nodes_reachable_on_edge_side(f, b)
}
}
cache the answer in edge e;
return answer;
}
|
74,503,960
| 74,508,747
|
Why don't I need to use the -MT option for dependency generation when I save my object files to a separate directory?
|
I have a (GNU)Makefile that gives the .o files a name that puts them in a separate directory. If I'm reading the GCC documentation on preprocessor options correctly, then all directory components and the file extension of the source file are stripped, .o is appended, and that's the name of the target. However, it seems to also prepend the path to where I store my object files automatically, without me manually specifying what to name the target with the -MT option. What am I misunderstanding?
I tried to attach a minimal working example (MWE) project for your convenience, but I cannot figure out how to do this on stackoverflow.
I have tried with and without -MT $@ in the CPPFLAGS. It doesn't seem to change a thing.
Makefile:
# Name directories
SRC_DIR := src
BUILD_DIR := build
OBJ_DIR := ${BUILD_DIR}/obj
DEP_DIR := ${BUILD_DIR}/dep
BUILD_DIRS := ${BUILD_DIR} ${OBJ_DIR} ${DEP_DIR}
# Name executable
BIN := ${BUILD_DIR}/howdy
# List directories where header files are found
_INCLUDE := include
INCLUDE := ${_INCLUDE:%=-I%}
# Make obj and dep files per source file
SRC := $(wildcard ${SRC_DIR}/*.cc) # Sneaky trick to get all .cc in a directory
OBJ := ${SRC:${SRC_DIR}/%.cc=${OBJ_DIR}/%.o}
DEP := ${OBJ:${OBJ_DIR}/%.o=${DEP_DIR}/%.d}
# Compiler and preprocessor setup
CXX := g++
CPPFLAGS = -MP -MMD -MF ${DEP_DIR}/$*.d
.PHONY: all # Output info and build if "make" or "make all" is invoked
all: ${BIN}
${BIN}: ${OBJ} # Link the object files to build the executable
${CXX} ${LDFLAGS} $^ -o $@
# Compile the source files into object files
${OBJ}: ${OBJ_DIR}/%.o: ${SRC_DIR}/%.cc | ${BUILD_DIRS}
${CXX} ${CXXFLAGS} ${CPPFLAGS} ${INCLUDE} -c $< -o $@
${BUILD_DIRS}: # Create directories as needed
mkdir -p $@
.PHONY: clean # Delete all object files, all dep files, and the executable
clean:
rm -rf ${BUILD_DIR}/*
-include ${DEP} # The dash makes make not fail if .d file not found
main.d:
build/obj/main.o: src/main.cc include/howdy.hh
include/howdy.hh:
|
This question doesn't have anything to do with make or makefiles. It's purely about how the GCC compiler's dependency generation works.
I agree with you that the behavior generated doesn't seem to match the documentation, unless we're misinterpreting what it says. Here's a test case, that doesn't need all the complexity of the makefile you provided:
$ touch /tmp/foo.c
$ gcc -MP -MMD -MF /tmp/foo.d -c -o /tmp/blahlbah.o /tmp/foo.c
$ cat /tmp/foo.d
/tmp/blahblah.o: /tmp/foo.c
It appears that, regardless of what the docs appear to say, the output target name by default (with no -MT) is the name provided with -o.
Perhaps what the docs mean is that if you don't provide -o and you don't provide -MT, then the result will be as documented. But, I think this is not a very successful way to document this.
In any event, I don't think StackOverflow is the right place to pursue this; you should contact the GCC folks for example at gcc-help@gnu.org
|
74,504,231
| 74,504,285
|
Follow pattern until negative then reverse using recursion
|
Trying to write a program that follows a simple pattern (x-y, x+y) as practice with recursion. Essentially taking a number, subtracting the second until reaching a negative value, then adding until reaching the original value. I understand my base case is reaching the original value, and my recursive case to subtract until negative but I can't quite figure out how to turn around and recurse back up to the original value.
void PrintNumPattern(int x, int y){
cout << x << " ";
if(x == //Original value//){
cout << endl;
}
else{
if(//has been negative//){
PrintNumPattern(x + y, y);
}
else{
PrintNumPattern(x - y, y);
}
}
}
int main() {
int num1;
int num2;
cin >> num1;
cin >> num2;
PrintNumPattern(num1, num2);
return 0;
}
|
Just print the value twice for each recursive call. You can't really know what the original value was, unless you pass it into the function:
void PrintNumPattern(int x, int y){
std::cout << x << " "; // Print "x" first
if ( x >= 0 ) { // If x is positive (or zero?) keep recursing
PrintNumPattern( x - y, y ); // Recursive call
std::cout << x << " "; // When recursive call is done, print the value again
}
}
With x = 100, and y = 7, output would be:
100 93 86 79 72 65 58 51 44 37 30 23 16 9 2 -5 2 9 16 23 30 37 44 51 58 65 72 79 86 93 100
|
74,504,975
| 74,505,986
|
c++ saving and reading a struct with a vector struct in it
|
I'm new to C++ so I'm not fully used to the syntax yet. I do know more than the basics of C# syntax tho, which I have been using for the better part of a year now, and I have 2 years of PHP and python to go with that.
I'm tryng to write a struct with a vector inside of it to a file, and read it back at a different moment;
struct inventoryItem
{
std::string itemName;
bool unlocked{false};
};
struct saveData
{
std::string userName{"John"};
int hunger{100};
int health{100};
int money{5};
std::vector<inventoryItem> inventory;
};
I'm saving it to the file like so:
void saveGame::createSave()
{
saveData saveObj;
inventoryItem newItem;
newItem.itemName = "shoes";
newItem.unlocked = true;
saveObj.inventory.push_back(newItem);
newItem.itemName = "knife";
saveObj.inventory.push_back(newItem);
// std::thread saveThis(save, saveObj);
// saveThis.join();
save(saveObj);
return;
}
void saveGame::save(saveData toSave)
{
std::fstream fileW(saveGame::fileName, std::ios_base::in);
if (!fileW.good() || !fileW.is_open())
{
system("exit");
} else
{
fileW.write((char *) &toSave, sizeof(saveData));
fileW.close();
}
return;
}
and I retrieve it like so:
saveGame::saveData saveGame::getSave()
{
std::fstream fileR(saveGame::fileName, std::ios_base::out);
saveData toRetrieve;
if (!fileR.good() || !fileR.is_open())
system("exit");
else
{
fileR.read((char *) &toRetrieve, sizeof(saveData));
}
return toRetrieve;
}
saveGame::saveData data = saveObj.getSave();
std::cout<<data.userName<<std::endl;
std::cout<<data.health<<std::endl;
std::cout<<data.inventory[0].itemName; // I've also tried looping through the vector, but this also did not work. Even when I don't try to access it, it will crash after it has processed the other pieces of data
Now, everything works correctly. And I can access all the data, except for the vector struct that's inside of it. As soon as it gets to that piece of data, the program crashes without a single error code. I do, however get a windows message saying "a.exe has stopped working" but it does not produce a Debug message. If possible, could you use simple terms in the explanation? I haven't gotten to advanced C++ yet. Thanks in advance
I've tried looping through the vector, not accessing it at all, and simply printing the first piece of data from it.
I am expecting this:
*CONSOLE OUTPUT*
John //username
100 // health
shoes // inventory.itemName (string)
true // inventory.unlocked (bool)
knife // inventory.itemName (string)
false // inventory.unlocked (bool)
But I am instead getting
*CONSOLE OUTPUT*
John //username
100 // health
and... BAM "a.exe has stopped working" without a debug message
|
A std::vector<> contains a length and a pointer to heap memory. You cannot save a vector like this:
vector<int> v = {1, 2, 3};
// the following line will save the length and the address of the array
// containing the data. NOT the data itself.
fileW.write((char *) &v, sizeof(v));
//...
std::vector<int> u;
// the following line will fill vector u with a length and a pointer to nowhere!
fileX.read((char *) &u, sizeof(u));
Note that the length and pointer to the data are PRIVATE members of std::vector<>. Manipulating them directly can only lead to undefined behavior.
To save a dynamic length array, you must first define a syntax for saving an array to your file, then a syntax for saving the individual items in your file.
In your particular case, you should also define a syntax for saving inventoryItem objects, because it contains a variable length string.
You can choose any syntax you want to save your data. It could be in binary format, with for example the length followed by the contents of the array, or use a library to save in a popular format, like xml or json, or .ini. No matter which solution you choose, you will need to write functions to save and read the types you defined:
struct inventoryItem
{
std::string itemName;
bool unlocked{false};
friend std::ostream& operator << (std::ostream& os, const inventoryItem& item)
{
return os << itemName << ' ' << (unlocked ? "true" : "false");
}
friend std::istream& operator >> (std::istream& is, inventoryItem& item)
{
std::string unl;
is >> itemName >> unl;
item.unlocked = (unl == "true");
return is;
}
};
struct saveData
{
std::string userName{"John"};
int hunger{100};
int health{100};
int money{5};
std::vector<inventoryItem> inventory;
friend std::ostream& operator << (std::ostream& os, const saveData& data)
{
os << data.userName << " "
<< data.hunger << " "
<< data.health << " "
<< data.money << " ";
os << data.inventory.size() << "\n";
for (size_t i = 0; i < data.inventory.size(); ++i)
os << data.inventory[i] << "\n";
}
friend std::istream& operator >> (std::istream& is, saveData& data)
{
is >> data.userName >> data.hunger >> data.health >> data.money;
size_t item_count = 0;
is >> item_count;
for (size_t i = 0; i < item_count; ++i)
{
inventoryItem item;
is >> item;
data.inventory.push_back(item);
}
return is;
}
};
NOTE: This code is not tested and may not even compile, it' only purpose is to show a simple way to stream dynamic data to/from a file. This very simple approach is usually too naive to be very useful. That's why you really should look into using a library, like boost::property_tree, to save into a more robust format.
|
74,505,069
| 74,506,674
|
How do I change the odd numbers to even in an array? C++
|
For this assignment, I have to write a program that removes the odd numbers from an array
and replaces them with even numbers. The array must have 10 elements and be initialized with the
following numbers: 42, 9, 23, 101, 99, 22, 13, 5, 77, 28.
These are the requirements:
Must use the values provided in my array.
Print the original array to the console.
Identify any odd values in the array and replace them with even values.
Display the updated array to the console.
This is the output I am going for:
The original array is: 42 9 23 101 99 22 13 5 77 28
Your even number array is: 42 18 46 202 198 22 26 10 154 28
I'm super new to programming, so this concept is difficult for me to grasp, so if someone could give guidance that would mean the world.
This is what I have so far
#include <iostream>
using namespace std;
int main()
{
int const size = 10;
int values[size] = { 42, 9, 23, 101, 99, 22, 13, 5, 77, 28 };
for (int i = 0; i < size; i++)
{
if (values[i] % 2 != 0)
{
cout << (values[i] * 2) << endl;
}
}
return 0;
}
output
It's multiplying the odd numbers, which is want I want, but not each one in their own line. Also the new even numbers need to be along with the original even numbers.
|
You mentioned that you are somehow new to programming. So, we need to adapt our answer to that fact. You will not yet know all the existing functions in the standard library. So, let us come up with a very easy solution.
Obviously we need to frist print the original unmodified date from the array. So, we will output the initial text and then iterate over all the slements in the array and output them as is.
Next, we show the second label string and then iterate again over all elements in the array. We the check for each value, if it is odd. If it is, then we print the double of this value, else, we show to unmodified value.
Please have a look at the below for one potential solution approach:
#include <iostream>
using namespace std;
int main() {
// Size of our array
int const size = 10;
// Arry with some random sample data
int values[size] = { 42, 9, 23, 101, 99, 22, 13, 5, 77, 28 };
// Show the original array
cout << "\nThe original array is: ";
for (int i = 0; i < size; ++i) cout << values[i] << ' ';
// Now show check for odd numbers
cout << "\nYour even number array is: ";
// Show result
for (int i = 0; i < size; ++i)
if (values[i] % 2 != 0)
cout << (values[i] * 2) << ' ';
else
cout << values[i] << ' ';
cout << '\n';
}
|
74,505,228
| 74,505,244
|
I get the error "fatal error: Tablero.h: No such file or directory" when trying to compile C++
|
I'm learning C++ and trying to create a class but when I try to compile my codeit gives me this error. As you can see, the file "Tablero.h" is in the same folder as the main.cpp file. Is there any other step that i should take for g++ to find the file "Tablero.h"?
Here you can see the error and the file being in the folder.
Also, vscode seems to recognize the exists, since it autocompletes the name and labels it as a file (archivo in spanish).
Here you can see how vscode recognizes the existence of the file.
Thanks in advance!
I tried compiling different projects and reopening vscode but nothing worked.
|
Try using #include "Tablero.h". Using <> checks headers in the standard library, but quotes "" look for headers in the local directory.
|
74,505,355
| 74,505,471
|
How can I make quick expression that's visible to assign to const?
|
I want to assign some value to a const, where it used to be something like
const int x = animal == "cat" ? 0 : 1;
But now, I want to make it so that if animal == cat, assign 0, and if dog returns 1, else 2 to the const. Well, in reality, it's not that simple but say something like use equation a, in this case, equation b, and equation c in this case.
Of course, I can always do something like
const int x = FunctionToHandleIt();
But the logic is so simple. I think it's much cleaner for the code to write out the expression right there so people can look at it and know exactly what's happening right then and there instead of going through the header and definition of the function to see what's happening.
What is the better way to handle a case like this to assign something to const that's more than a few lines? But, not worth making a whole function for it?
|
With the help of a lambda function, there is no need to specify the definition of another function somewhere in the code.
const string animal = "dog";
const int x = [animal]() {
if (animal == "cat")
return 0;
else if (animal == "dog")
return 1;
else
return 2;
}();
cout << x << endl;
The variable animal is captured to be validated in the inner code block. The respective values are returned after that.
|
74,505,475
| 74,505,614
|
c++ object lifetime extension rules with member initializers
|
In this talk, the author mentions lifetime extension rules extend to member initializers based on the standard. I see the opposite though, i.e. ~Y is called before "Hello" is printed below. Is the author referring to something else?
#include <iostream>
using namespace std;
struct Y {
~Y() {
cout << __PRETTY_FUNCTION__ << "\n";
}
Y() {
cout << __PRETTY_FUNCTION__ << "\n";
}
};
struct X {
~X() {
cout << __PRETTY_FUNCTION__ << "\n";
}
X(const Y& y) : ref(y) {
cout << __PRETTY_FUNCTION__ << "\n";
}
const Y &ref;
};
Y gety() {
return {};
}
X getx() {
return gety();
}
int main() {
const X &ref = X{Y{}};
cout << "Hello\n";
}
The output is
Y::Y()
X::X(const Y&)
Y::~Y()
Hello
X::~X()
Edit:
I see a difference with the following update that does aggregate initialization
struct X {
~X() {
cout << __PRETTY_FUNCTION__ << "\n";
}
/*
X(const Y& y) : ref(y) {
cout << __PRETTY_FUNCTION__ << "\n";
}
*/
const Y &ref;
};
int main() {
const X &ref = X{Y{}};
cout << "Hello\n";
}
in which case the output is
Y::Y()
Hello
X::~X()
Y::~Y()
|
It applies only in the case of aggregate initialization, because otherwise there is a constructor call and the prvalue would be bound to the reference parameter of that constructor, not directly to the reference member.
Also, it does not apply to aggregate initialization with parentheses instead of braces in C++20 and later. (There is a specific exception for this case.)
|
74,505,859
| 74,506,401
|
how I make that two variables points at the same spot in C++?
|
I'm working with an array of objects where some of them should have the literal same parameter, so when it changes it also changes in all of them.
I tried using pointers, so that every parameter points at the same memory, but I really don't really know how to do it. In my code something is happening because it compiles, but when I change the variable that should change all at once, it change alone, I could change it all manually, but I don't think that is the optimal way of doing it.
ex:
this line is to create the object, I give it the direction of memory of two nodes and a section,
elementos[i].Set_elemento(&nodos[numero_nodoi-1],&nodos[numero_nodoj-1],&secciones[numero_seccion-1]);
and here, I'm supposed to do the thing, but it doesn't do anything.
void Set_elemento(Nodo *nodo_i, Nodo *nodo_j, Seccion *seccion_){
Nodo*p1=NULL;
p1=&nodoi;
p1=nodo_i;
Nodo*p2=NULL;
p2=&nodoj;
p2=nodo_j;
Seccion*j=NULL;
j=&seccion;
j=seccion_;
}
thanks for your help and I'm sorry I don't speak English.
|
To dereference a ponter, you use * before the pointer.
void Set_elemento(Nodo* nodo_i, Nodo* nodo_j, Seccion* seccion_) {
nodoi = *nodo_i;
nodoj = *nodo_j;
seccion = *seccion_;
}
It gets the objects at the pointers' addresses and sets your member variables to them.
Though I think your entire method of achieving what you want to do is wrong.
Having each node store the entire node and copy it is very very... very dumb. Instead, you should store the addresses and allocate the pointers. Thus change your nodoi, nodoj, seccion member variables to pointers and you wouldn't need to dereference anything.
Then you could just copy the addresses (only 8 bytes) instead of dereferencing/copying the entire object and having to somehow keep track of all that for all nodes:
Nodo* nodoi, nodoj;
Seccion* seccion;
void Set_elemento(Nodo* nodo_i, Nodo* nodo_j, Seccion* seccion_) {
nodoi = nodo_i;
nodoj = nodo_j;
seccion = seccion_;
}
|
74,506,123
| 74,506,203
|
How ceil function works in c++?
|
When I execute this code the value of ans1, ans2 is 50002896 and 50005000.
I know there is some issues with ceil function but was not able to figure out the exact cause.
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long ans1 = 0, ans2 = 0;
for (long long i = 1; i <= 10000; i++)
{
ans1 = ans1 + ceil((float)i / 1);
ans2 = ans2 + i;
}
cout << ans1 << " " << ans2 << endl;
}
|
The source of the problem is not the ceil function, but rather that not all integers can be represented accuratly as floating point values. Some more info about floating point representation: Wikipedia IEEE 754.
The following code is a minimal demonstration of the same issue that causes your issue:
float f1 = 100000000;
f1++;
std::cout << std::to_string(f1) << std::endl;
[Wrong] Output (expected: +1):
100000000.000000
One approach would be to use double instead of float.
This will not solve the principle issue, but will make the range of representable integers a lot bigger:
double f1 = 100000000;
f1++;
std::cout << std::to_string(f1) << std::endl;
Output:
100000001.000000
A side note: better to avoid #include <bits/stdc++.h>, see: Why should I not #include <bits/stdc++.h>?.
|
74,506,702
| 74,506,771
|
why is the iterator showing address instead of value in the loop?
|
`
vector<int> nums;
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
vector<int> res;
res.push_back(nums.front());
vector<int>::iterator it = nums.begin();
vector<int>::iterator it2 = res.begin();
++it;
cout << "it2 -> " << *it2 << endl;
cout << "it + it2 " << *it + *it2 << endl;
while(it != nums.end())
{
res.push_back(*it + *it2);
cout << "it : " << *it << endl;
cout << "it2 : " << *it2 << endl;
cout << "pushed " << (*it + *it2) << " ";
it++;
it2++;
}
it = nums.begin();
while(it != nums.end())
{
cout << *it << " ";
++ it;
}
cout << endl;
it2 = res.begin();
while(it2 != res.end())
{
cout << *it2 << " ";
++it2;
}
cout << endl;
`
The output of the above is :
it2 -> 1
it + it2 3
it : 2
it2 : 17858448
pushed 17858450 it : 3
it2 : 17825984
pushed 17825987 1 2 3
1 3 17825987
I can't understand why the value of *it2 is normal outside the loop but inside it, it's showing the address.
I was trying to find the running sum of a 1d array using vectors. I learning iterators and hence am interested in understanding exactly why the above code is not working.
|
Those aren't addresses, they are garbage integers.
Your code is suffering from iterator invalidation. When you add an item to a vector you potentially invalidate any iterator that is pointing to it. This happens because adding an element to a vector may cause the vector to reallocate the memory it uses to hold it's elements. If this happens then you are left with an iterator that is no longer pointing at the correct memory, so you get garbage values.
The simple fix is to use integer offsets instead of iterators for this code
vector<int>::iterator it = nums.begin();
size_t off2 = 0;
++it;
cout << "res[off2] -> " << res[off2] << endl;
cout << "it + res[off2] " << *it + res[off2] << endl;
while(it != nums.end())
{
res.push_back(*it + res[off2]);
cout << "it : " << *it << endl;
cout << "res[off2] : " << res[off2] << endl;
cout << "pushed " << (*it + res[off2]) << " ";
it++;
off2++;
}
Although since you seem to be always using the last item from res an even simpler fix would be to use res.back(). Without the printing that gives
vector<int>::iterator it = nums.begin();
++it;
while(it != nums.end())
{
res.push_back(*it + res.back());
it++;
}
An earlier version of this post was incorrect, thanks to Pepijn for putting me straight.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.