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 |
|---|---|---|---|---|
72,578,796 | 72,578,872 | Zero cost non-macro solution for calling a function in the correct order | I have a code base where some common functions need to be called in order before and after some unique function
Eg:
common1();
common2();
unique(); // note: unique returns void but can have any number of arguments
common3();
common4();
A problem is, anytime a new unique is made, or anytime more commonX functions are added then every place in the code where this pattern is required has to be made to match.
One solution is to use a macro
#define DO_UNIQUE_CORRECTLY(unique_code_block) \
common1(); \
common2(); \
unique_code_block \
common3(); \
commont(); \
...
void someFunc1(arg1) {
DO_UNIQUE_CORRECTLY({
unique1(arg1);
});
}
void someFunc2(arg1, arg2) {
DO_UNIQUE_CORRECTLY({
unique2(arg1, arg2);
});
}
That works. The question is: Is there a non-Macro C++ way to do this with ZERO overhead AND discourage mistakes AND and not be overly verbose to use.
Note: if it's not obvious, the "not overly verbose" requirement means the functions I'm calling might have lots of parameters with very large types. Having to copy and paste the list of types = "overly verbose"
One solution I know of is something like this
class Helper {
Helper() {
common1();
common2();
}
~Helper() {
common3();
common4();
}
}
void someFunc1(arg1) {
Helper helper;
unique1(arg1);
}
void someFunc2(arg1, arg2) {
Helper helper;
unique2(arg1, arg2);
}
The problem with this solution IMO is it's seems easy to insert stuff unaware that you're doing it wrong
void someFunc2(arg1, arg2) {
Helper helper;
doExtra1(); // bad
unique2(arg1, arg2);
doExtra2(); // bad
}
Like imagine that common2 is perfRecordStartTime and common3 is perfRecordEndTime. In that case you don't want anything extra before/after unique2.
You could argue the same issue with the macro
void someFunc2(arg1, arg2) {
DO_UNIQUE_CORRECTLY({
doExtra1(); // bad
unique2(arg1, arg2);
doExtra2(); // bad
});
});
But rename DO_UNIQUE_CORRECTLY to say TIME_FUNCTION and Helper to TimingHelper
void someFunc2(arg1, arg2) {
TIME_FUNCTION({
doExtra1(); // clearly bad
unique2(arg1, arg2);
doExtra2(); // clearly bad
});
});
vs
void someFunc2(arg1, arg2) {
TimingHelper helper;
doExtra1(); // bad?
unique2(arg1, arg2);
doExtra2(); // bad?
}
TimingHelper so doing magic stuff here. Maybe it's just an opinion but this helper pattern seems more error prone for this case than the macro pattern.
Is it also some possibly super tiny but non-zero cost calling into the Helper constructor/destructor vs the inline code of the macro?
Another is to use lambdas
template<typename Func>
void DoUniqueCorrectly(Func fn) {
common1();
common2();
fn();
common3();
common4();
}
void someFunc1(arg1) {
DoUniqueCorrectly([&]() {
unique1(arg1);
});
}
void someFunc2(arg1, arg2) {
DoUniqueCorrectly([&]() {
unique2(arg1, arg2);
});
}
The problem with this one is as far as I understand, lambdas are really building an object/tuple to hold on to references to the closed over arguments. To put another way it's almost like this
void someFunc2(type1 arg1, type2 arg2)
std::tuple<const type1&, const type2&> c = {arg1, arg2};
DoUniqueCorrectly([&]() {
unique2(std::get<0>(c), std::get<1>(c));
});
}
So there is overhead of this tuple being initialized. Will that all be optimized out so the code will have the same overhead as the macro?
Let me add one more wrinkle. uniqueX can be a more complex function call. For example
void SomeClass::someFunc2(arg1, arg2) {
DO_UNIQUE_CORRECTLY({
getContext()->getThing()->unique2(arg1, arg2);
});
}
Is there another solution?
PS: I get that if any overhead exists it's small. I still want to know if there is a zero overhead non-macro C++ way of doing this.
| The decorator you presented can be easily extended to pass an arbitrary amount of arguments to your invocable:
template<typename Func, class... Args>
void DoUniqueCorrectly(Func&& fn, Args&&... args)
{
common1();
common2();
std::invoke(std::forward<Func>(fn), std::forward<Args>(args)...);
common3();
common4();
}
then your use cases are called as:
void someFunc1(arg1) { DoUniqueCorrectly(unique1, arg1); }
void someFunc2(arg1, arg2) { DoUniqueCorrectly(unique2, arg1, arg2); }
Everything forwarded to an inlinable function template (DoUniqueCorrectly). No extra or intermediate objects. Plus std::invoke will "generate" the correct call syntax for any type of callable (function pointers, lambdas, pointers to member functions etc etc) something that a MACRO doesn't do out of the box.
The ammended example (the wrinkle) would be called as
DoUniqueCorrectly(&Thing::unique2, o.getContext()->getThing(), 1, 2);
i.e. pointer to member function called from object pointer. std::invoke has no problem.
Demo
|
72,578,875 | 72,579,043 | C++ - weird thread behavior when pass vector to method | I wrote the following code and noticed a weird behavior.
#include <iostream>
#include <vector>
#include <thread>
void withVectorArg(double waitTime, std::vector<int> q = {}) {
std::cout << "[withVectorArg] waitTime: " << waitTime << "s" << '\n';
std::thread thread([&waitTime]() {
std::cout << "[withVectorArg] waitTime: " << waitTime << "s" << '\n';
});
thread.detach();
}
void withoutVectorArg(double waitTime) {
std::cout << "[withoutVectorArg] waitTime: " << waitTime << "s" << '\n';
std::thread thread([&waitTime]() {
std::cout << "[withoutVectorArg] waitTime: " << waitTime << "s" << '\n';
});
thread.detach();
}
int main() {
withVectorArg(1);
std::this_thread::sleep_for(std::chrono::seconds(1));
withoutVectorArg(1);
while (true) {}
return 0;
}
The output of this code is:
[withVectorArg] waitTime: 1s
[withVectorArg] waitTime: 3.38411e-312s
[withoutVectorArg] waitTime: 1s
[withoutVectorArg] waitTime: 1s
Both methods do exactly the same and do not use the q variable, yet the first one somehow changes the value of waitTime.
Does someone know why this happens?
Thank you!
| Both your functions are undefined behavior.
The reason is that you're starting a thread, detaching it and exiting the function immediately. The thread however is capturing the parameter BY REFERENCE and thus when the code in the thread body is executed (that MAY happen AFTER you already returned from the function) the local variable that the reference is bound to does not exist any more (that local was destroyed when returning from the function).
What happens when you enter the UB realm is simply undefined, trying to explain the exact weird behavior is a waste of time.
|
72,579,592 | 72,579,654 | dependent types without helper type | Given typename T and int N, the templated value below generates a null function pointer of the type:
int (*) (T_0, ..., T_N)
While the code works, I don't like that it pollutes the namespace with the Temp bootstrap helper - Temp is required because types can't be enclosed in parentheses. For example, none of the following are valid.
(int (*)((int))
((int (*)(int)))
(int (*)( (I,T)... ))
The last entry shows how I would like to expand T into a list of N Ts - which of course isn't valid. It's a trick to make T depend on I but with a value only of T, thanks to the comma operator.
As a workaround, I'm forced to create the one-shot type Temp templated to make T depend on int, or in this case, I. Its usage as Temp<T,I> is valid because it doesn't enclose types in parenthesis.
However, like I said, I want to get rid of Temp because it pollutes the namespace. In the code below I restate the problem and demonstrate some attempted workarounds which sadly, all fail. For the record, I think an equivalence between template <typename T, int> using Temp = T; and template <... template<typename T1, int N1> typename Temp=T> should be allowed.
Followup: When I original published this question, I didn't know exactly why extra parentheses were disallowed, and I'm still not sure why some of my attempts failed. For example:
decltype(w<T,N>())...
result_of<w<T,N>()>::type...
I don't see any parentheses around types!
#include <iostream>
#include <typeinfo>
// Problem, #1
// This is a one-shot helper than pollutes the namespace
template <typename T, int>
using Temp = T;
// Idea #1
// Make the one-shot helper actuall useful, where ... represents either
// type or non-type parameters.
// Result
// Not possible.
//template <typename T, ...>
//using Dependent = T;
// Idea #2
// Make the types dependent within the template declaration
// Result
// Probably not possible
//template <typename T, int N, template<typename T1, int N1> typename F=T>
// Idea #6
// Replace the lambda with a struct (not shown)
// Result
// Crashes gcc
template <typename T, int N>
auto a =
[]<size_t... I>
(std::index_sequence<I...>) {
// Problem #2
// Function type declaration won't parse with extra parentheses
//return (int (*)( (I,T)... ))nullptr;
// Idea #3
// Move the templated helper into the function
// Result
// Not possible
//template <typename T, int>
//using Temp = T;
// Idea #4
// Replace the templated helper with a templated lambda which *is*
// allowed inside functions.
// Result
// Still requires parentheses, still breaks function type declaration
//auto w = []<typename T1, int N1>() -> T1 {};
//return (int (*)( decltype(w<T,N>())... ));
// Idea #5
// result_of (which is a template) instead of decltype
// Result
// Doesn't work even without parentheses, not sure why
//return (int (*)( result_of<w<T,N>>... ));
//return (int (*)( result_of<w<T,N>()>::type... ));
// Idea #7
// Use std::function
// Result
// Can't get function pointer from std::function
// Idea #2 implementation
//using F<T,I> = T;
//return (int (*)( F<T,I>... ))nullptr;
// So far, only this works:
return (int (*)( Temp<T,I>... ))nullptr;
}
(std::make_index_sequence<N>{});
int main () {
auto b = a<int, 4>;
std::cout << typeid(b).name() << std::endl;
}
| You can replace Temp<T,I> with std::enable_if_t<(void(I), true), T>.
Function type declarations won't parse extra parentheses
that actually works! Why?
Types can't be enclosed in parentheses. But the first argument of enable_if_t is an expression rather than a type, so ( ) is allowed there.
|
72,579,804 | 72,585,799 | How can I fix a C++20 compile error involving concepts and friends? | Let's say I start with this simple example of the use of a C++20 "concept":
template <typename T>
concept HasFoo = requires( T t )
{
t.foo();
};
template <HasFoo T>
void DoFoo( T& thing )
{
thing.foo();
}
class FooThing
{
public:
void foo() {}
};
int main(int argc, const char * argv[]) {
FooThing x;
DoFoo( x );
return 0;
}
This compiles, and the concept verifies that the FooThing class has a method foo. But suppose I want to make the method foo private, and call DoFoo on the FooThing from
another method of FooThing. So I try adding a friend declaration:
class FooThing
{
private:
void foo() {}
friend void DoFoo<FooThing>( FooThing& thing );
};
This results in an error message: FooThing does not satisfy HasFoo because t.foo() would be invalid: member access into incomplete type FooThing.
To reassure myself that the concept really is essential to this problem, I tried doing without it,
template <typename T>
void DoFoo( T& thing )
{
thing.foo();
}
and then the error goes away. Is there any way to fix the error while keeping the concept?
If I try the suggestion of an attempted answer and add a forward declaration
template<typename T> void DoFoo(T&);
before the class, then the compile error goes away, but I get a link error saying that DoFoo(FooThing&) or DoFoo<FooThing>(FooThing&) is an undefined symbol.
| Yes! This friend declaration compiles and links:
class FooThing
{
//public:
void foo() {}
template<HasFoo T>
friend void DoFoo(T&);
};
I would have to poke around to find the exact standardese, but I know there is a rule that multiple declarations referring to the same template must have the same constraints (typename T is not allowed here).
|
72,579,840 | 72,581,405 | What is the best way to create a 'using' declaration involving members of incomplete types? | I have a very simple CRTP skeleton structure that contains just one vector and a private accessor in the base class. There is a helper method in the CRTP class to access it.
#include <vector>
template<typename T>
class CRTPType {
// Will be used by other member functions. Note it's private,
// so declval/decltype expressions outside of friends or this class
// cannot see it
auto& _v() {
return static_cast<T *>(this)->getV();
}
};
class BaseType : public CRTPType<BaseType> {
friend class CRTPType<BaseType>;
std::vector<int> v;
//For different base types this impl will vary
auto& getV() { return v; }
};
So far so good. Now I want to add a using declaration to CRTPType that will be the type that _v() returns. So ideally, one could do something like the following:
template<typename T>
class CRTPType {
//Will be used by other member functions
auto& _v() {
return static_cast<T *>(this)->getV();
}
using vtype = decltype(std::declval<CRTPType<T>>()._v());
};
The problem is that the type is incomplete, so I cannot use any decltype/declval expressions within CRTPType.
Is there a clean way around this that breaks encapsulation as little as possible? Ideally in C++14, but I would be interested if there are any newer language features that help.
| If you don't care so much where and how exactly the using declaration appears, then you can avoid the issue without much changes for example by putting the using declaration into a nested class:
template<typename T>
class CRTPType {
//Will be used by other member functions
auto& _v() {
return static_cast<T *>(this)->getV();
}
struct nested {
using vtype = decltype(std::declval<CRTPType<T>>()._v());
};
};
The issue in your original code is that using declarations are implicitly instantiated with the class template specialization and the point of implicit instantiation of CRTPType<BaseType> is before the definition of BaseType because the latter uses the former as a base class (which are required to be complete and are therefore implicitly instantiated).
Nested member classes are on the other hand specified not to be implicitly instantiated with the class template specialization and instead only when they are required to be complete. In other words the point of instantiation of the using declaration will now be immediately before the namespace scope declaration which actually, directly or indirectly, uses nested::vtype.
Another alternative is to make the using declaration a template:
template<typename T>
class CRTPType {
//Will be used by other member functions
auto& _v() {
return static_cast<T *>(this)->getV();
}
template<typename U = T>
using vtype = decltype(std::declval<CRTPType<U>>()._v());
};
Member templates can not be implicitly instantiated with the containing class template specialization either. It may be necessary to use the U = T construction and only use U in using = . The reason is that if the type on the right-hand side is not dependent on a template parameter, the compiler is allowed to check whether it can be instantiated immediately after the definition of the template, which is exactly what is not possible and we want to avoid. The program may therefore be ill-formed, no diagnostic required if only T is used. (I am really not 100% sure this applies here, but Clang does actually complain.)
Another possibility is to move the using declaration outside the class, in which case it is obvious that it will not be implicitly instantiated with it:
template<typename T>
class CRTPType;
template<typename T>
using CRTPType_vtype = decltype(std::declval<CRTPType<T>>()._v());
template<typename T>
class CRTPType {
//Will be used by other member functions
auto& _v() {
return static_cast<T *>(this)->getV();
}
};
Variations using nested classes or namespaces coupled with using declarations in the enclosing namespace can hide the additional name from the outside.
With all of the above you still need to be careful that nothing else in the instantiation of CRTPType<BaseType> or in the definition of BaseType actually indirectly uses vtype. If that happens you may be back to the original problem, potentially even depending on the declaration order of members (although that technically is not standard-conform behavior of the compilers).
In any case, you need to friend the CRTPType<BaseType> in BaseType or mark getV in BaseType as public.
|
72,580,240 | 72,581,421 | include SFML Library in VSCode "SFML/Graphics.hpp no such file or directory" gcc | I've seen other question's relating to this and most if not all that I could find have some round about way of getting SFML to compile and run in VSCode I'm hoping that there is a way to simply append the SFML/include directory to the compilers includes this works with the intelliSense code completion and it correctly knows the location of the SFML Library. intelliSense screenshot.(The extra errors you can see in the screenshot disappear when the file is saved).
So ultimately what I would like to know or have help with is getting the SFML library to compile and run without the need for the boilerplate from GitHub that seems to be commonly used thank you.
Main.cpp
#include <SFML/Graphics.hpp>
int main()
{
float windowHeight = 400;
float windowWidth = 400;
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "Rougelike");
sf::Texture texture;
if (!texture.loadFromFile("res/player-sprite.png"))
return 0;
sf::Sprite sprite;
sprite.setTexture(texture);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
window.clear();
window.draw(sprite);
window.display();
}
}
This is my c_cpp_properties.json.
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${default}",
"A:/SFML-2.5.1/include/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.19041.0",
"compilerPath": "A:/mingw32/bin/g++.exe",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "windows-gcc-x86",
"compilerArgs": ["-I A:/SFML-2.5.1/include/**"]
}
],
"version": 4
}
| In VS Code, c_cpp_properties.json specifies parameters used by the editor itself (like compiler path, C++ standard, include directories for IntelliSense purposes; see documentation here), but doesn't specify build tasks - that is the job of tasks.json. In your .vscode folder, create tasks.json file like this:
{
"version": "2.0.0",
"tasks": [
{
"label": "Compile SFML executable",
"type": "cppbuild",
"command": "g++",
"args": [
"-o",
"${workspaceFolder}/main.exe",
"-IA:/SFML-2.5.1/include/",
"-LA:/SFML-2.5.1/lib/",
"${workspaceFolder}/main.cpp",
"-lsfml-graphics",
"-lsfml-window",
"-lsfml-system"
],
"group": {
"kind": "build",
"isDefault": true
},
}
]
}
Here, we created a new task named "Compile SFML executable". This task compiles main.cpp into main.exe, while giving g++ all the necessary information about SFML: include directories (-I flag), library directories (-L) and main SFML libraries themselves for linker input. Specifically, -l{library_name} links lib{library_name}.a, which is, in our case, import library of stubs referring to dynamic library {library_name}-2.dll (this name is coded inside import library), which can be found in A:/SFML-2.5.1/include/bin/ folder (assuming you installed MinGW version of SFML libraries, which you should have, since you use MinGW G++ compiler). {library_name} here refers to sfml-window, sfml-system and sfml-graphics, which, judging by your code, are the only ones you need right now. Note that dynamic libraries have to be copied to executable folder (or wherever else system dynamic loader will be able to find them) before running.
You can run the task by Ctrl-Shift-P -> Tasks: Run Task -> Compile SFML executable, and after that run resulting executable outside of VS Code. Alternatively, you can use F5 or Ctrl-F5 within VS Code to run executable with or without debugging respectively, where the executable will be built prior to run according to a default launch configuration's preLaunchTask, which by default is set to our task (because of "isDefault": true).
Also note that if you want to do debug builds/runs, you should link to {library_name}-d instead of {library_name} (and copy {library_name}-d-2.dll into executable folder to run) instead. Creating separate task (like "Compile SFML executable Debug") with appropriate -l{library_name}-d flags can be useful for this. You can then choose which build task to perform before run by removing "isDefault": true from both configurations and using Ctrl-Shift-P -> C/C++: {Debug / Run} C/C++ File and choosing launch configuration with appropriate preLaunchTask from the list.
|
72,580,340 | 72,586,142 | Issues reimplementing some C# encryption stuff in C++ using cryptopp | So I have this piece of C# code:
void Decrypt(Stream input, Stream output, string password, int bufferSize) {
using (var algorithm = Aes.Create()) {
var IV = new byte[16];
input.Read(IV, 0, 16);
algorithm.IV = IV;
var key = new Rfc2898DeriveBytes(password, algorithm.IV, 100);
algorithm.Key = key.GetBytes(16);
using(var decryptor = algorithm.CreateDecryptor())
using(var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read)) {
CopyStream(cryptoStream, output, bufferSize);
}
}
}
and I am trying to translate this into C++ with CryptoPP.
So this is what I have written:
void decrypt(std::ifstream& in_file, std::ofstream& out_file, std::string_view password, size_t bufSize) {
using namespace CryptoPP;
// Get IV
byte iv[16];
in_file.read(reinterpret_cast<char*>(iv), sizeof(iv));
// Read cypher
std::string cypher;
while (in_file && cypher.size() != bufSize) {
char c;
in_file.read(&c, 1);
cypher.push_back(c);
}
// Get key
byte key[16];
PKCS5_PBKDF2_HMAC<SHA1> pbkdf2;
pbkdf2.DeriveKey(key, sizeof(key), 0, reinterpret_cast<const byte*>(password.data()), password.size(), iv, sizeof(iv), 100);
// Decrypt
CTR_Mode<AES>::Decryption decrypt(key, sizeof(key), iv);
std::string output;
StringSource(cypher, true, new StreamTransformationFilter(decrypt, new StringSink(output)));
// Write output to file
out_file.write(output.data(), output.size());
}
However, from this function, I am only getting back trash data. What could I be doing wrong?
Thanks
Tuxifan!
| So I found the solution! First of all, as @mbd mentioned, C# uses CBC by default. Additionally, I need to cut away the rest of the data like this:
while ((cipher.size() % 16) != 0) {
cipher.pop_back();
}
|
72,580,779 | 72,581,131 | Binaries missing after successful build? | I have a CMake project that I use to generate a Visual Studio solution, which I then try to compile. For some reason, the library file after compilation is nonexistent. I've searched my entire project folder, and cannot find any library files. Here's my CMake setup:
Project root:
cmake_minimum_required(VERSION 3.22)
project(ShadowContainers)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
include_directories(include/)
add_subdirectory(library)
...
library subdirectory:
add_library(libShadows shadows.tpp ../include/shadows.hpp)
set_target_properties(libShadows PROPERTIES LINKER_LANGUAGE CXX) # a tpp and an hpp aren't enough to make the system certain it's c++
target_compile_features(libShadows PRIVATE cxx_std_23)
The MSbuild output contains these lines:
Done Building Project "C:\Users\[..]\projects\Shadow Array\library\libShadows.vcxproj" (default targets).
Done Building Project "C:\Users\[..]\projects\Shadow Array\library\libShadows.vcxproj.metaproj" (default targets).
Even if libShadows is the only target in my project, it's nowhere in my project directory.
Has anybody else had this experience? Any help is appreciated. Thanks!
Edit:
To compile the project, I have tried:
My typical process (working directory = the project root):
cmake .
msbuild ShadowContainers.sln
An alternate process (working directory also project root):
mkdir build
cd build
cmake ..
cmake --build .
Both have produced the same result, albeit with VS and CMake files in different places. No library is outputted either way.
| I was able to find the issue. CMake (and conventions for that matter) do not see a .tpp as a code file (similarly to how they treat header files). Thus, I was trying to compile a target with no legitimate code files. Template-only libraries are not libraries at all, so I should not be attempting to compile this standalone, and should instead put the .hpp and .tpp as the include in my projects!
|
72,580,796 | 72,580,861 | Template class as a function parameter [C++] | The premise of the question is how to pass a templated class as a parameter to another function or at least get the same effect:
Below is a stripped-down version of my code
template<uint8_t _bus>
class Com {
public:
uint8_t write() { return _bus; /* does something with template param */}
};
class Instruction
{
public:
int member;
void transmitFrame(char *msg) {
member = Com.write(msg); /* need to pass in Com object somehow */
}
};
main(){
Com<8> myCom;
Instruction myInstruction;
char[] msg = {'h', 'e', 'l', 'l', 'o'};
myInstruction.transmitFrame(msg);
}
The code above will not compile.
My first thought would be to just extend the Com class however as far as I am aware you can not extend class templates. My second thought would be to have a template inside a template? (so make the Instruction class a template class with a template of the Com template) But I am in the weeds on that one and not sure if that is possible.
The Com object has been instantiated by the time I am trying to use the Instruction class. So somehow, I need to get the templated Com object into the Instruction class so that I can access it.
At that point I am out of ideas...
| You appear to be trying to call write on the Com class directly, rather than an instance.
You likely want to pass an instance of Com to transmitFrame, but to do that you have to pass the template info.
template <uint8_t N>
void transmitFrame(Com<N> &com, char *msg) {
com.write(msg); /* need to pass in Com object somehow */
}
Or if you know the template value will be 8.
void transmitFrame(Com<8> &com, char *msg) {
com.write(msg); /* need to pass in Com object somehow */
}
|
72,580,871 | 72,580,922 | C++ substring not giving me the correct result | I have the following code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file;
string s;
//file contains the following
//id="123456789"
//Note: There is no spaces at the end
file.open("test.txt", ios::in);
getline(file, s);
s = s.substr(s.find("\"")+1, s.length()-1);
cout << s << endl;
return 0;
}
The results print:
123456789"
Why is there a quote at the end?
A weird thing is that when I change s.length()-1 to s.length()-5, the code work how I wanted it to.
What is the problem here?
| The 2nd parameter of string::substr() is a count, not an index, like you are treating it.
In your example, s.length()=14, so you are asking for 14-1=13 characters starting at the index +1 past the 1st " character (3+1=4), but there are only 10 characters remaining from that position onward. That is why the 2nd " character is being included in the substring.
Use string::find() again to find the index of the 2nd " character, and then subtract the two indexes to get the length between them, eg:
auto start = s.find('\"') + 1;
auto stop = s.find('\"', start);
s = s.substr(start, stop-start);
start will be the index +1 past the 1st " character (3+1=4), and stop will be the index of the 2nd " character (13). Thus, the length you get is 13-4=9 characters.
Another way to handle this would be to put the string into an istringstream and then use the std::quoted I/O manipulator to extract the substring between the " characters, eg:
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream file("test.txt");
string s;
getline(file, s);
istringstream iss(s);
iss.ignore(3);
iss >> quoted(s);
cout << s << endl;
return 0;
}
|
72,580,960 | 72,580,991 | Why is my class an incomplete type inside itself? | class test {
public:
test(int i) : t(10) {
cout << "cst" << i << endl;
}
static test ins;
const test t;// 1
};
On line 1, the compiler fails with an error:
incomplete type is not allowed
Why is that?
| The compiler parses code from top to bottom. When the compiler encounters the declaration of t, it hasn't yet seen the end of the declaration of test, hence why test is an "incomplete type" at that location. The compiler doesn't know yet if there are any more data members following t, so it doesn't know how much space to reserve for t within each instance of test.
Basically, a class (or struct) cannot include a non-static instance of itself. Doing so would lead to a recursive declaration that never ends until the compiler fails.
However, a class/struct can include a pointer or reference to itself, since a pointer/reference has a fixed size at compile-time. For example, this is how linked-lists are implemented.
|
72,581,214 | 72,581,549 | Should I mark the move constructor & move assignment operator as deleted in this case? | I hope to prevent the users from creating new instance through the constructor, so I mark the constructor as a private method.
What's more, I need to provide a method to return an type which is used to automatically manage the life of the instance. I don't hope the user to use the instance of Foo class directly, I hope they always use std::shared_ptr<Foo> instead.
#include <iostream>
#include <memory>
class Foo : public std::enable_shared_from_this<Foo> {
private: //the user should not construct an instance through the constructor below.
Foo(int num):num_(num) { std::cout << "Foo::Foo\n"; }
public:
Foo(const Foo&) = delete;
Foo(Foo&&) = default;
Foo& operator=(const Foo&) = delete;
Foo& operator=(Foo&&) = default;
public:
~Foo() { std::cout << "Foo::~Foo\n"; }
int DoSth(){std::cout << "hello world" << std::endl; return 0;}
std::shared_ptr<Foo> getPtr() { return shared_from_this();}
static std::shared_ptr<Foo> Create() {
Foo* foo = new Foo(5);
return std::shared_ptr<Foo>(foo);
}
private:
int num_;
};
int main()
{
auto sp = Foo::Create();
sp->DoSth();
Foo& foo = *sp.get();
auto sp1 = foo.getPtr();
Foo foo1(std::move(foo));
std::cout << sp.use_count() << std::endl;
}
I am not sure whether or not I should mark the move constructor & move assignment operator as deleted.
What I am worried about is that there is a thread safety issue if one thread is invoking move constructor while the other thread is calling some member function at the same time. How do you think about it?
| I think your question answers itself.
I don't hope the user to use the instance of Foo class directly, I hope they always use std::shared_ptr<Foo> instead.
followed by
Foo foo1(std::move(foo));
demonstrating the ability to use an instance of Foo directly, not managed by a shared pointer. Defining the move constructor as deleted prevents this thing you want users to avoid.
|
72,581,561 | 72,581,569 | Xtensor random::randn returning number number below lower bound and above upper bound | I am trying to generate random numbers of shape {10} and range between -0.5 and 0.5
#include <iostream>
#include <xtensor/xio.hpp>
#include <xtensor/xrandom.hpp>
int main() {
xt::xarray<double> a = xt::random::randn<double>({10}, -0.5, 0.5);
std::cout << a;
return 0;
}
but it's returning an array
{-0.432735, -0.573191, -0.269675, -1.435692, -0.418144, -0.607127,
-0.350702, -0.913972, -0.494892, 0.027733}
where -0.573191 is smaller and -1.435692 is bigger than range
| According to the documentation for randn:
template<class T, class S, class E = random::default_engine_type>
auto xt::random::randn(const S& shape, T mean = 0, T std_dev = 1,
E& engine = random::get_default_random_engine())
The function draws numbers from std::normal_distribution and you've set the mean value to be -0.5 and the standard deviation to be 0.5. These are not lower and upper bounds.
You may want to use the rand function instead:
template<class T, class S, class E = random::default_engine_type>
auto xt::random::rand(const S& shape, T lower = 0, T upper = 1,
E& engine = random::get_default_random_engine())
This draws numbers from std::uniform_real_distribution - so, it's not the same thing, but it has a lower and an upper bound.
|
72,582,238 | 72,878,217 | Opencv Decode Gray code pattern tutorial 3D scanner Problems | I used a ready-made tutorial code from the opencv library in C ++, the link is as follows:
https://docs.opencv.org/3.4/dc/da9/tutorial_decode_graycode_pattern.html
This is the title of this code (Decode Gray code pattern tutorial)
The job of this code is to take photos as a pattern and then read the calibration values from the yaml file and display the photos in the form of points cloud in the 3D scan output. I used his default photos. Also from his yaml files, all of which are at the following address.
https://github.com/opencv/opencv_extra/tree/4.x/testdata/cv/structured_light/data
The code is compiled correctly, but the problem is that in the example above it is not written what arguments to give to achieve the desired result. Displays its code output as follows:
But the code I get is as follows:
The values that I give the program as an argument are as follows:
./main images.yml calibrationParameters.yml 3 3 0 0
Please help me to execute the code correctly and bring it to the highest display quality. Can you suggest where exactly I look at the code?
| The correct parameters passed to the program should be
./main images.yml calibrationParameters.yml 1280 800
The parameters 1280 and 800 represent projector's width and height
I found this information in the author's github repo, you can find it here
I compile the code in the tutorial and use the parameter above, works great (OpenCV version: 4.5.5)
|
72,582,371 | 72,582,394 | How to catch datatype overflow exception in C++? | Here, base may overflow beyond limits of int, causing runtime error, at which point I intend to catch the Runtime error raised, and handle it, so I tried the try-catch block, but it is not being caught.
int base=1;
try
{
base *= 10;
//some code
}
catch(...)
{
//some code
}
| You can't. Arithmetic overflow on signed integral types causes undefined behavior, not an exception. If such overflow happens in your program, it is too late. You can't do anything to save the program. It is already in undefined state at that point.
You should check for potential overflow before you perform the multiplication.
|
72,582,599 | 72,596,707 | Why is there segmentation fault in this merge sort? | I compiled this code on different compilers, but all of them gave runtime error. Can someone tell me what's wrong with this code?
void merge(int *str, int beg, int mid, int end) {
int *arr = new int[end - beg + 1];
int k = 0;
int i = beg;
int j = mid + 1;
while (i <= mid && j <= end) {
if (str[i] < str[j]) {
arr[k] = str[i];
i++;
k++;
} else {
arr[k] = str[j];
j++;
k++;
}
}
while (i <= mid) {
arr[k] = str[i];
i++;
k++;
}
while (j <= end) {
arr[k] = str[j];
//here i got buffer overrun while writing to arr
j++;
k++;
}
for (i = beg; i <= end; i++) {
str[i] = arr[i - beg];
}
delete[] arr;
}
void merge_sort(int *str, int beg, int end) {
if (beg >= end)
return;
int mid = (end - beg) / 2;
merge_sort(str, beg, mid);
merge_sort(str, mid + 1, end);
merge(str, beg, mid, end);
}
This code is almost same as I found on Sanfoundry, but that one is working but mine got some errors.
| Your computation of the mid point in merge_sort is incorrect: instead of int mid = (end - beg) / 2; you should write:
int mid = beg + (end - beg) / 2;
Note also that your API is confusing as mid seems to be the end of the index of the last element of the left half and end the index of the last element of the right slice. It is much simpler and less error prone to specify mid as the index of the first element of the right half and end the index of the first element after the right slice. With this convention, the initial call is:
merge_sort(array, 0, array_length);
Here is a modified version using type size_t for index and length variables:
void merge(int *str, size_t beg, size_t mid, size_t end) {
int *arr = new int[end - beg];
size_t i = beg;
size_t j = mid;
size_t k = 0;
while (i < mid && j < end) {
if (str[i] <= str[j]) {
arr[k++] = str[i++];
} else {
arr[k++] = str[j++];
}
}
while (i < mid) {
arr[k++] = str[i++];
}
while (j < end) {
arr[k++] = str[j++];
}
for (i = beg; i < end; i++) {
str[i] = arr[i - beg];
}
delete[] arr;
}
void merge_sort(int *str, size_t beg, size_t end) {
if (end - beg >= 2) {
size_t mid = beg + (end - beg) / 2;
merge_sort(str, beg, mid);
merge_sort(str, mid, end);
merge(str, beg, mid, end);
}
}
|
72,582,729 | 72,582,743 | ‘int main()’ previously defined here | I did this code and faced an error that I can't understand what it is. I run this program in VS code and compilation was successful but getting an compilation error in GFG portal.
#include <iostream>
using namespace std;
/*
* Create classes Rectangle and RectangleArea
*/
int l,b, result;
class Rectangle
{
public:
void display()
{
cout<<l <<" "<< b<<endl;
}
};
class RectangleArea : public Rectangle
{
public:
void read_input()
{
cin >> l >> b;
}
void display()
{
result = l* b;
cout<<result;
}
};
int main()
{
/*
* Declare a RectangleArea object
*/
RectangleArea r_area;
/*
* Read the width and height
*/
r_area.read_input();
/*
* Print the width and height
*/
r_area.Rectangle::display();
/*
* Print the area
*/
r_area.display();
return 0;
}
And this is the error I got. Help me.
This is the GFG problem that I'm doing.
| Don't paste the main function, the portal adds it again to the source so it appears twice.
|
72,582,804 | 72,585,305 | How to add parameters to section names in Catch2 | I'm using Catch2 to create a set of tests for some C++ legacy code and I have a function that I would like to test for a good amount of values. I have found that I can use the GENERATE keyword to create a data generator variable that will repeat the following scenario for each of the generated values, but my only issue is that when I launch the tests, I cannot distinguish which execution is for each value.
So for a minimal example like:
TEST_CASE("Evaluate output of is_odd() function") {
auto i = GENERATE(1, 3, 5);
SECTION("Check if i is odd"){ // <-- I want to fit the actual value of i in here.
REQUIRE(is_odd(i));
}
}
So if I launch the tests and I specify -s to see passed tests as well, I would like to see something like:
-------------------------------------------
Evaluate output of is_odd() function
Check if 1 is odd
-------------------------------------------
...
-------------------------------------------
Evaluate output of is_odd() function
Check if 3 is odd
-------------------------------------------
...
-------------------------------------------
Evaluate output of is_odd() function
Check if 5 is odd
-------------------------------------------
I have tried creating a string containg i and concatenating it to the SECTION's name, but it didn't work, is there some way to achieve this?
| This is possible, but not very obvious from the documentation. What you're looking for is a dynamic section:
TEST_CASE("Evaluate output of is_odd() function") {
auto i = GENERATE(1, 3, 5);
DYNAMIC_SECTION("Check if " << i << " is odd"){
REQUIRE(is_odd(i));
}
}
|
72,582,935 | 72,583,195 | How can I store a std::bind function pointer? | Here is the code I am using
#include <functional>
#include <iostream>
#include <thread>
class Context {
private:
std::thread thread;
bool running;
void run() {
while (running) {
if (function != nullptr) {
function();
function = nullptr;
}
}
}
void (*function)();
public:
Context() : running(true) { thread = std::thread(&Context::run, this); }
~Context() {
running = false;
thread.join();
}
template <typename T, typename... Args> void call(T function, Args... args) {
this->function = std::bind(function, args...);
}
};
// Here are some test functions
void f1() { std::cout << "f1" << std::endl; }
void f2(int a) { std::cout << "f2(" << a << ")" << std::endl; }
void f3(int a, int b) {
std::cout << "f3(" << a << ", " << b << ")" << std::endl;
}
int main() {
Context context;
context.call(f1);
context.call(f2, 1);
context.call(f3, 1, 2);
return 0;
}
I want this class to create a thread that will run some functions.
The thread will be created when the class is created and will be stopped
when the class is destroyed.
In order to run a function, you can call the Context::call function with the
function to be called and the arguments.
f2(2);
becomes
context.call(f2, 2);
and
f3(3, 4);
becomes
context.call(f3, 3, 4);
However I am getting errors when I try to compile this file :
t.cpp: In instantiation of 'void Context::call(T, Args ...) [with T = void (*)(); Args = {}]':
t.cpp:55:15: required from here
t.cpp:42:31: error: cannot convert 'std::_Bind_helper<false, void (*&)()>::type' to 'void (*)()' in assignment
42 | this->function = std::bind(function, args...);
| ~~~~~~~~~^~~~~~~~~~~~~~~~~~~
| |
| std::_Bind_helper<false, void (*&)()>::type
t.cpp: In instantiation of 'void Context::call(T, Args ...) [with T = void (*)(int); Args = {int}]':
t.cpp:56:15: required from here
t.cpp:42:20: error: cannot convert 'std::_Bind_helper<false, void (*&)(int), int&>::type' to 'void (*)()' in assignment
42 | this->function = std::bind(function, args...);
| ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
t.cpp: In instantiation of 'void Context::call(T, Args ...) [with T = void (*)(int, int); Args = {int, int}]':
t.cpp:57:15: required from here
t.cpp:42:20: error: cannot convert 'std::_Bind_helper<false, void (*&)(int, int), int&, int&>::type' to 'void (*)()' in assignment
I know this code is unsafe and has flaws but I used mutexes and security measures in the real implementation. This example is just the minimal to reproduce the error.
| You can make use of std::function. In particular, replace void (*function)() with std::function<void ()> function as shown below:
class Context {
private:
//other code here
std::function<void ()> function;
};
Working demo
|
72,582,947 | 72,584,212 | How to make contiguous data in class C++ | I am using Visual C++ on Windows 10.
I want to make class Vector4 such that it has members x, y, z, t and they stored contiguously to provide operator[] and other functions:
class Vector4
{
public:
float operator[](size_t idx)
{
return &x + idx;
}
public:
float x, y, z, t;
}
But I found out that such implementation works not on every compiler(On Visual C++ it works well).
And I dont know how to fix it, maybe write something like this: class alignas(sizeof(float)) Vector4;
| From: C++ - Class contiguous data
You can use #pragma pack(1) with e.g. MSVC and gcc, or #pragma pack 1 with aCC.
As said in the answer #pragma pack(1) will disables padding and guarantees that the members are contiguous:
That basically disables padding and guarantees that the floats are contiguous. However, to ensure that the size of your class is actually 4 * sizeof(float), it must not have a vtbl, which means virtual members are off-limits.
See also the official C++ documentation: Implementation defined behavior control
The answer gives two ways:
#pragma pack(1)
class FourFloats
{
float f1, f2, f3, f4;
};
and
#pragma pack(push, 1)
class FourFloats
{
float f1, f2, f3, f4;
};
#pragma pack(pop)
|
72,582,965 | 72,583,061 | 8/16-bit atomics on 32/64-bit processors | In C++11 and C11 it is possible to use 8- and 16-bit atomics. Are there any pitfalls of using them on actual modern 32- and 64-bit CPUs? Are they lock-free? Are they slower than native-size atomics? I'm interested in both what standard says about it and how it's actually implemented on common architectures.
| There are no common pitfalls or any reason to expect any.
The standard say nothing about it, but basically nothing about performance guarantees in general. But in practice, if atomic<int> is lock-free, it's almost certain that atomic<int16_t> and atomic<int8_t> are also lock-free. I'd be surprised if there are any mainstream implementations where that's not true.
x86 hardware supports them directly, at the same speed as other operand-sizes. e.g. mov load/store, and for atomic RMWs, lock xadd byte [rdi], al exists in byte operand-size as well as word/dword/qword. Same for all other atomic RMW instructions, including xchg and cmpxchg.
Other ISAs may have minor slowdowns for narrow stores (and maybe also loads), like a cycle of extra latency for a pure-load or pure-store. This is pretty much negligible compared to inter-core latency, and pretty minor even when a cache line is already hot. See Are there any modern CPUs where a cached byte store is actually slower than a word store? (it's not unique to atomic operations.)
Most non-x86 ISAs also have byte and 16-bit versions of the same instructions they provide for atomic RMWs, like ARM ldrexb / strexb.
Of course for an atomic RMW, it's also safe to do an RMW of the containing word, and that can be done "naturally" with minimal extra work for a fetch_or or other bitwise boolean, or a CAS. But I think most widely used ISAs have direct support for byte and 16-bit operations, so don't need that trick.
|
72,583,780 | 72,584,018 | Getting stdout using vscode mingw gcc | I wanted to extent my c knowledge to c++. Using Win10, I installed VSCode and mingw following the tutorials.
Next I created a Hello World test file.
It compiles properly without errors. However when I run it from a terminal window, I do not get any output.
I am sure its a stupid beginners mistake...
#include <iostream>
using namespace std;
int main(){
std::cout << "Hello Moon!";
std::cout.flush();
return 0;
}
compiling:
Kompilierung wird gestartet...
D:\msys64\mingw64\bin\g++.exe -fdiagnostics-color=always -g3 -Wall "D:\CPLUSPLUS\programs\hello world\hello world.cpp" -o "D:\CPLUSPLUS\programs\hello world\hello world.exe"
Die Kompilierung wurde erfolgreich abgeschlossen.
console:
PS D:\CPLUSPLUS\programs\hello world> "hello world.exe"
hello world.exe
PS D:\CPLUSPLUS\programs\hello world>
so obviously it runs the exe without complaint, however I do not see any output...
Any hints/ideas?
| Thanks quimby! that did the job!
actually ist not my c++ vscode ignorance but the one of powershell (coming from cmd...)
so you are right: powershell did NOT run my program but rather just echo the quoted string.
so ones needs the & operator to do the job.
Problem solved
Thanks again.
|
72,583,820 | 72,584,186 | C# references to C++ CLR x32 and x64 | I created a C++ project in Visual Studio Class library CLR (.NET Framework):
#pragma once
using namespace System;
#ifdef _M_X64
namespace MyDLL64 {
#else
namespace MyDLL32 {
#endif
public ref class MyClass
{
public: static String^ Foo(String^ arg)
{
String^ str = arg->ToUpper();
return str;
}
};
}
Then I compiled two libraries(x86 and x64).
Thereafter I add them to references in my C# project
and added their methods to the code:
String res = "";
if (IntPtr.Size == 8)
{
res = MyDLL64.MyClass.Foo("test string");
}
else
{
res = MyDLL32.MyClass.Foo("test string");
}
Console.WriteLine(res);
But I am getting this error:
System.BadImageFormatException: "Could not load file or assembly 'MyDLL64, Version=1.0.8197.24341, Culture=neutral, PublicKeyToken=null', or one of their dependencies. An attempt was made to load a program with an invalid format."(or MyDLL32... if arch is 64 bit).
By the way, this code starts correctly without exceptions:
String res = "";
if (IntPtr.Size == 8)
{
res = MyDLL64.MyClass.Foo("test string");
}
if (1 > 2)
{
res = MyDLL32.MyClass.Foo("test string");
}
Console.WriteLine(res);
So how properly add x32 and x64 C++CLR dlls to my Any CPU C# DLL?
|
So how properly add x32 and x64 C++CLR dlls to my Any CPU C# DLL?
You can't. AnyCPU just means that the self process can be executed either as a 32 or 64 bit one depending on the architecture but once a 64 bit process is spawned it cannot access 32 bit images and vice versa.
If your C# project references native images, then instead of building one AnyCPU image you must create two separate images just like in case of the C++ project.
Specify x86 and x84 targets for the solution. And then if your 32/64-bit C++ dlls are named differently, then you can edit your .csproj file like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Platform)'=='x86'">
<PlatformTarget>x86</PlatformTarget>
<DefineConstants>$(DefineConstants);X86</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="'$(Platform)'=='x86'">
<Reference Include="MyDLL32"/>
</ItemGroup>
<PropertyGroup Condition="'$(Platform)'=='x64'">
<PlatformTarget>x64</PlatformTarget>
<DefineConstants>$(DefineConstants);X64</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="'$(Platform)'=='x64'">
<Reference Include="MyDLL64"/>
</ItemGroup>
</Project>
And then the C# code can have similar #if directives than the C++ one:
String res = "";
#if X64
res = MyDLL64.MyClass.Foo("test string");
#else
res = MyDLL32.MyClass.Foo("test string");
#endif
Console.WriteLine(res);
But IMHO it would be nicer if the C++ images used the same namespaces so the C# code does not need the #if directives and the different images could be handled purely in the .csproj file (in which case you don't need the DefineConstants either).
|
72,584,080 | 72,673,998 | Ambiguous Class Template Conversion | How would one add a template constructor to the class so that copy initialization from complex to complex is performed explicitly and without ambiguity? Is there a solution that is compiler and C++ version/standard agnostic? Is there an approach that only requires definition of a constructor without an additional operator overload?
I included the template copy constructor and operator overload (last two methods defined in the class) but the compiler gives me the following message.
Compilation error
main.cpp: In function ‘void testTemplateConstructor()’:
main.cpp:74:27: error: conversion from ‘complex<float>’ to ‘complex<double>’ is ambiguous
complex<double> cd = cf;
^~
main.cpp:35:5: note: candidate: complex<T>::operator complex<X>() [with X = double; T = float]
operator complex<X>(){
^~~~~~~~
main.cpp:29:5: note: candidate: complex<T>::complex(complex<X>&) [with X = float; T = double]
complex(complex<X>& arg) {
^~~~~~~
This is the test case being utilized.
void testTemplateConstructor() {
complex<float> cf{1.0f, 2.0f};
complex<double> cd = cf;
Assert(cf.real()==cd.real(), "Real parts are different.");
Assert(cf.imag()==cd.imag(), "Imaginary parts are different.");
}
template <typename T> class complex{
private:
typedef complex<T> complexi;
T real_;
T imag_;
public:
complex(){
real_ = 0;
imag_ = 0;
}
complex(T a, T b){
real_ = a;
imag_ = b;
}
complex(T a){
real_ = a;
}
complex(complex<T>& comp){
real_ = comp.real_;
imag_ = comp.imag_;
}
template <typename X>
complex(complex<X>& arg) {
real_ = arg.real_;
imag_ = arg.imag_;
}
template <typename X>
operator complex<X>(){
return complex<T>();
}
};
| This is the solution I was looking for, this works with the C++11 standard and compiler versions as old as x86_64 gcc 4.7.1 and clang 3.4.1. The only difference apart from the use of static_cast is the use of getters.
using namespace std;
template <typename T> class complex{
public:
typedef complex<T> complexi;
T real_;
T imag_;
public:
complex(){
real_ = 0;
imag_ = 0;
}
complex(T a, T b){
real_ = a;
imag_ = b;
}
complex(T a){
real_ = a;
}
complex(const complex<T>& comp){
real_ = comp.real_;
imag_ = comp.imag_;
}
template <typename X>
complex(const complex<X>& rhs){
real_ = static_cast<T>(rhs.real());
imag_ = static_cast<T>(rhs.imag());
}
T real() const {
return real_;
}
T imag() const {
return imag_;
}
};
|
72,584,085 | 72,584,167 | std::bit_cast vs reinterpret_cast in file I/O | How should one cast pointers to char*/const char*? Using reinterpret_cast? Or probably std::bit_cast?
A simple example:
#include <iostream>
#include <fstream>
#include <bit>
int main( )
{
std::uint32_t var { 301 };
{
std::ofstream file { "myfile.bin" };
file.write( std::bit_cast<const char*>( &var ), sizeof( var ) );
}
std::uint32_t var2 { 10 };
{
std::ifstream file { "myfile.bin" };
file.read( std::bit_cast<char*>( &var2 ), sizeof( var2 ) );
}
std::cout << var2 << '\n';
}
This seems to works fine. Also replacing all the std::bit_casts with reinterpret_casts works fine too.
So which one is more correct in this case? And what about using std::byte* instead of char* for file I/O (though I tried it and it did not compile)?
| First of, of course all of this only applies if var and var2 have the same type and this type is trivially-copyable. A very common mistake is to try to write and read non-trivially-copyable types like std::string in this way, which is fundamentally wrong.
std::bit_cast is not generally safe, because there is no guarantee that const char* and std::uint32_t* use the same representation for the pointer values. They technically don't even need to have the same size. Whether you are going to come into contact with a platform where this is the case, is a different question.
The intended purpose of std::bit_cast is to reinterpret the object representation of one value of a given type into another type, giving you a (possibly different) corresponding value of the target type. (For example if you know the representation used for float and int, both of them are the same size and you have an integer value from which you want to retrieve a float value corresponding to the same representation.)
For pointers this is usually not really what you want. You want the value of the pointer to be preserved (or to get a pointer value to a related object or the object representation). How the representations of the original and converted pointer value relate is secondary.
reinterpret_cast does the above. reinterpret_cast<const char*> is the standard approach and is almost as correct as you can get. There are some defects in the standard regarding how exactly the result of this cast can be used, but for practical purposes you can just assume that it will always give you a pointer to the first element of the object representation (interpreted as a char array), which is what you want write to write to the file.
The same applies to the read case (except that const can not be used on reads for obvious reasons; const isn't required for the write case either, but shows intent more clearly).
If you want a to stay completely in the realm of what the standard currently specifies, I think the following should be fine (except for missing error and end-of-file checking, which could incur undefined behavior):
int main( )
{
std::uint32_t var { 301 };
{
std::ofstream file { "myfile.bin" };
char buf[sizeof(var)]{};
std::memcpy(buf, &var, sizeof(var));
file.write(buf, sizeof(buf));
}
std::uint32_t var2 { 10 };
{
std::ifstream file { "myfile.bin" };
char buf[sizeof(var2)]{};
file.read(buf, sizeof(buf));
std::memcpy(&var2, buf, sizeof(buf));
}
std::cout << var2 << '\n';
}
But practically, any compiler will have the expected behavior with reinterpret_cast, so there isn't much of a point to this.
If you were to design the file IO operations nowadays, you would probably use std::byte instead of char in the interface, but std::byte has been introduced only with C++17 while iostream has been around since (before) C++98. You can't convert a std::byte* to a const* without another reinterpret_cast, so it is pointless to go through it.
|
72,584,271 | 72,601,353 | OpenGL: Access violation reading location when calling glDrawArrays | I'm trying to make a Minecraft-like game, and currently, I am stuck on getting chunks to work in a list. It works fine when I do it like this:
Chunk ch1(0, 0, 0);
ch1.fillVertices();
ch1.updateVBO();
Chunk ch2(0, 0, 17);
ch2.fillVertices();
ch2.updateVBO();
ch1.draw();
ch2.draw():
but I can't put them in a list and use them from there:
std::list<Chunk> chunks;
chunks.emplace_back(0, 0, 0);
chunks.emplace_back(16, 0, 0);
for (Chunk& chunk : chunks) {
chunk.fillVertices();
chunk.updateVBO();
}
for (Chunk& chunk : chunks) {
chunk.draw();
}
because I get a "Access violation reading location" error message at glDrawArrays.
Here's the chunk code:
struct Chunk {
Block* blocks = nullptr;
unsigned int VAO = 0;
unsigned int VBO = 0;
float chunkPosX = 0, chunkPosY = 0, chunkPosZ = 0;
std::vector<Vertex> vertices;
int chunkPosUniformLoc = 0;
Chunk(float x = 0.0f, float y = 0.0f, float z = 0.0f) : chunkPosX(x), chunkPosY(y), chunkPosZ(z) {
blocks = new Block[CHUNK_WIDTH * CHUNK_DEPTH * CHUNK_HEIGHT];
if (!blocks)
CLOG("Couldn't mallocate blocks!");
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glUseProgram(sp);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
chunkPosUniformLoc = glGetUniformLocation(sp, "chunkPos");
}
void updateVBO() {
if (vertices.size() != 0) {
glBindVertexArray(VAO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &(vertices[0]), GL_DYNAMIC_DRAW);
}
}
void fillVertices() {
vertices.clear();
for (int y = 0; y < CHUNK_HEIGHT; y++) {
for (int x = 0; x < CHUNK_WIDTH; x++) {
for (int z = 0; z < CHUNK_DEPTH; z++) {
unsigned int id = blocks[y * CHUNK_WIDTH * CHUNK_DEPTH + x * CHUNK_DEPTH + z].id;
BlockInfo bi = globalRe->getInfo(id);
if (blocks[y * CHUNK_WIDTH * CHUNK_DEPTH + x * CHUNK_WIDTH + z].id == BLOCKID::AIR)
continue;
if (z == 15 || !blocks[y * 16 * 16 + x * 16 + (z + 1)].isSolid()) { // Front
vertices.emplace_back( x, y, 1 + z, bi.textCoord[0][0].left, bi.textCoord[0][0].bottom );
vertices.emplace_back( 1 + x, y, 1 + z, bi.textCoord[0][0].right, bi.textCoord[0][0].bottom );
vertices.emplace_back( 1 + x, 1 + y, 1 + z, bi.textCoord[0][0].right, bi.textCoord[0][0].top );
vertices.emplace_back( 1 + x, 1 + y, 1 + z, bi.textCoord[0][0].right, bi.textCoord[0][0].top );
vertices.emplace_back( x, 1 + y, 1 + z, bi.textCoord[0][0].left, bi.textCoord[0][0].top );
vertices.emplace_back( x, y, 1 + z, bi.textCoord[0][0].left, bi.textCoord[0][0].bottom );
}
// Other faces
}
}
}
}
}
void draw() {
glBindVertexArray(VAO);
glUseProgram(sp);
glUniform3f(chunkPosUniformLoc, chunkPosX, chunkPosY, chunkPosZ);
auto s = vertices.size();
glDrawArrays(GL_TRIANGLES, 0, s);
}
~Chunk() {
delete[] blocks;
}
};
Using:
GLAD
GLFW
OpenGL Core 4.3
C++ 20
Intel HD-Graphics 5500
I suspect that there's something wrong with my memory-management and there's corrupted memory somewhere although the Visual Studio Debugger doesn't say so. I just don't understand why it works as separate variables but not in a list.
| The buffer bound to GL_ARRAY_BUFFER isn't part of the VAO state. The VAO stores the buffer used for each attribute (the GL_ARRAY_BUFFER at the time glVertexAttribPointer was called), and the GL_ELEMENT_ARRAY_BUFFER.
So your updateVBO is writing to the latest constructed chunk's VBO instead of writing to VBO of the chunk it's called on.
Fix: bind the VBO before glBufferData
|
72,584,272 | 72,584,296 | Color disappears when light is used in opengl | glLoadIdentity();
glTranslatef(0.0f + deltaA - deltaD, 0.0f + deltaQ - deltaE, 0.0f + deltaW - deltaS);
glRotatef(_rotate_x, 1, 0, 0);
glRotatef(_rotate_y, 0, 1, 0);
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidSphere(20, 15, 15);
If I write the code like this, the red color looks good.
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLoadIdentity();
glTranslatef(0.0f + deltaA - deltaD, 0.0f + deltaQ - deltaE, 0.0f + deltaW - deltaS);
glRotatef(_rotate_x, 1, 0, 0);
glRotatef(_rotate_y, 0, 1, 0);
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidSphere(20, 15, 15);
glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);
But if I use a light like this, it's white. What's the reason?
How can I solve this problem?
| See Basic OpenGL Lighting. When lighting (GL_LIGHTING) is enabled, the render color is taken from the material parameters (glMaterial). If you still want to use the current color attribute (set by glColor), you need to enable GL_COLOR_MATERIAL
and to set the color material parameters (glColorMaterial):
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
|
72,584,831 | 72,584,861 | Why i can't assign value to the 2d vector of char? | I am working on a code that needs vectors of vectors (2d vector) and I am trying to initialize this with '.' with the below code.
vector< vector< char >> vec;
for(int i=0; i < N ; i++)
{
vector<char> temp('#', N);
vec.push_back(temp);
}
I also tried
vector< vector < char >> vec;
for(int i=0; i<N ; i++)
{
vector< char > temp();
temp.assign('.' , N);
vec.push_back(temp);
}
My code is assigning value to the vector, but assigned value isn't '.' but something else. When I tried to print it, it is printing some weird gibberish output.
I also tried the simple way to assign value to my vector and it worked well. Below is the code.
vector< vector < char >> vec;
for(int i=0; i<N ; i++)
{
vector< char > temp;
for(int j=0;j<N;j++)
{
temp.push_back('#');
}
vec.push_back(temp);
}
Why does the first and second code isn't working similar to third. Or are they meant to be used with integers only and not char.
| The problem is that you have supplied the arguments in the wrong order when creating the temp vector.
Replace vector<char> temp('#', N); with
vector<char> temp(N,'#');
Do the same with std::vector::assign.
|
72,585,207 | 72,586,102 | Extending 2 arguments [x, y] into variable size parameter pack [x, ... x, y] | I'm writing a custom multi layer perceptron (MLP) implementation in C++. All but the last layer share one activation function foo, with the final layer having a separate activation bar. I'm trying to write my code such that it's able to handle models of this type with a varying number of layers, like at this Godbolt link, reproduced below. Unfortunately, as written, I've had to hardcode the parameter pack for activation functions, and thus the code in the link only compiles for N = 5.
Is there a way to create a custom parameter pack from the two activation functions which is able to "left-extend" the first argument, such that I can then compile the code above (after suitably updating the call to computeIndexedLayers in computeMlp? Specifically, I'm thinking of some utility which can yield parameter packs like:
template <size_t N, typename ActivationMid, typename ActivationLast>
struct makeActivationSequence {}; // What goes here?
makeActivationSequence<0>(foo, bar) -> []
makeActivationSequence<1>(foo, bar) -> [bar]
makeActivationSequence<2>(foo, bar) -> [foo, bar]
makeActivationSequence<3>(foo, bar) -> [foo, foo, bar]
makeActivationSequence<4>(foo, bar) -> [foo, foo, foo, bar]
...
Looking at the details of std::index_sequence I believe something similar might work here, but it's unclear to me how I'd modify that approach to work with the two different types.
Please note also that I'm specifically limited to C++14 here due to some toolchain issues, so solutions that take advantage of e.g. if constexpr (as in the linked std::index_sequence details) won't work.
Code from the above Godbolt link, reproduced below for completeness:
#include <cstddef>
#include <utility>
#include <cstdio>
template <size_t LayerIndex, typename Activation>
void computeIndexedLayer(
const Activation& activation) {
printf("Doing work for layer %zu, activated output %zu\n", LayerIndex, activation(LayerIndex));
}
template <
std::size_t... index,
typename... Activation>
void computeIndexedLayers(
std::index_sequence<index...>, // has to come before Activation..., otherwise it'll get eaten
Activation&&... activation) {
(void)std::initializer_list<int>{
(computeIndexedLayer<index + 1>(
std::forward<Activation>(activation)),
0)...};
}
template <size_t N, typename ActivationMid, typename ActivationLast>
void computeMlp(ActivationMid&& mid, ActivationLast&& last) {
computeIndexedLayers(std::make_index_sequence<N>(),
std::forward<ActivationMid>(mid),
std::forward<ActivationMid>(mid),
std::forward<ActivationMid>(mid),
std::forward<ActivationMid>(mid),
std::forward<ActivationLast>(last)
);
}
int main() {
computeMlp<5>([](const auto& x){ return x + 1;}, [](const auto& x){ return x * 1000;});
// Doesn't compile with any other choice of N due to mismatched pack lengths
// computeMlp<4>([](const auto& x){ return x + 1;}, [](const auto& x){ return x * 1000;});
}
| You can't return a parameter pack from functions, so makeActivationSequence as you described is impossible. However, you can pass mid and last directly to computeIndexedLayers, and there utilise pack unfolding pairing them with, respectively, midIndex template parameter pack and lastIndex template parameter (in this case, there's exactly one lastIndex, so it's not a template parameter pack, but it's not hard to change/generalise if needed) deduced from two corresponding std::index_sequence arguments. Like this:
#include <cstddef>
#include <utility>
#include <cstdio>
template <size_t LayerIndex, typename Activation>
void computeIndexedLayer(Activation&& activation) {
printf("Doing work for layer %zu, activated output %zu\n", LayerIndex, activation(LayerIndex));
}
template <std::size_t... midIndex, std::size_t lastIndex,
typename ActivationMid, typename ActivationLast>
void computeIndexedLayers(
std::index_sequence<midIndex...> midIdxs,
std::index_sequence<lastIndex> lastIdxs,
ActivationMid&& mid, ActivationLast&& last) {
(void)std::initializer_list<int>{
(computeIndexedLayer<midIndex + 1>(mid), 0)...,
(computeIndexedLayer<lastIndex>(std::forward<ActivationLast>(last)), 0)};
}
template <size_t N, typename ActivationMid, typename ActivationLast>
void computeMlp(ActivationMid&& mid, ActivationLast&& last) {
computeIndexedLayers(std::make_index_sequence<N - 1>(), std::index_sequence<N>{},
std::forward<ActivationMid>(mid), std::forward<ActivationLast>(last));
}
int main() {
computeMlp<6>([](const auto& x){ return x + 1;}, [](const auto& x){ return x * 1000;});
}
Godbolt link
Also note that in computeMlp both mid and last are forwarded, but at computeIndexedLayers only last is. It's done to avoid potential repeated move from mid, which could cause troubles if ActivationMid contains some state and is not a trivially movable type.
C++17
Since C++17 supports fold expressions, pretty ugly std::initializer_list hack in computeIndexedLayers can be replaced:
template <std::size_t... midIndex, std::size_t lastIndex,
typename ActivationMid, typename ActivationLast>
void computeIndexedLayers(
std::index_sequence<midIndex...> midIdxs,
std::index_sequence<lastIndex> lastIdxs,
ActivationMid&& mid, ActivationLast&& last) {
(computeIndexedLayer<midIndex + 1>(mid), ...);
computeIndexedLayer<lastIndex>(std::forward<ActivationLast>(last));
}
C++20
Templated lambdas in C++20 let us get rid of computeIndexedLayers altogether and deduce template parameters and parameter packs for lambda, defined and immediately invoked within computeMlp:
template <size_t N, typename ActivationMid, typename ActivationLast>
void computeMlp(ActivationMid&& mid, ActivationLast&& last) {
[&]<std::size_t... midIndex, std::size_t lastIndex>(
std::index_sequence<midIndex...> midIdxs,
std::index_sequence<lastIndex> lastIdxs){
(computeIndexedLayer<midIndex + 1>(mid), ...);
computeIndexedLayer<lastIndex>(std::forward<ActivationLast>(last));
}(std::make_index_sequence<N - 1>(), std::index_sequence<N>{});
}
|
72,585,673 | 72,585,890 | Modifying a cv::Rect inside a cv::Mat in C++ | I'm pretty new to openCV and would like to ask what seems like a easy question.
I have an image in the form of a cv::Mat and I would like to change only a small part of the matrix. I've read that using a cv::Rect is the correct way but I can't seem to find a way to only modify that little ROI.
Here's the code:
cv::Mat img = cv::Mat::zeros(msg->height, msg->width, CV_64FC1);
cv::Rect rect(100, 100, 20, 50);
All I want to do is do linear tranformation to the rect and add asign it to the same part of the img.
Something like:
int a=0.1, b=20;
rect = rect*a + b;
Thanks in advance.
| OpenCV's cv::Mat has a constructor that creates an ROI image referncing another image:
cv::Mat::Mat(const Mat & m, const Rect & roi)
Using this constructor will cause the new cv::Mat to share the data with the original one:
No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it.
The reference counter, if any, is incremented.
So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m.
You can also use the operator() for that:
Mat cv::Mat::operator() (const Rect & roi) const
In your case you can do something like the following:
#include <opencv2/core/core.hpp>
int main()
{
int h = 320;
int w = 640;
cv::Mat img = cv::Mat::ones(h, w, CV_64FC1);
cv::Rect rect(100, 100, 20, 50);
cv::Mat roi(img, rect); // alternatively you can use: cv::Mat roi = img(rect);
double a = 0.1;
double b = 20;
roi = roi * a + b; // this will modify the relevant area in img
return 0;
}
|
72,585,860 | 72,599,834 | Change the number type of a CGAL mesh (lazy exact -> double) | I have a triangle CGAL mesh with the exact kernel (EK, EMesh3, EPoint3) and I want to convert it to the same mesh with the inexact kernel (K, Mesh3, Point3). My solution consists in taking each vertex and each face of the exact mesh and adding them one by one to an empty inexact mesh. Is there a more straightforward way?
Mesh3 Convert(EMesh3 emesh) {
const size_t nvertices = emesh.number_of_vertices();
const size_t nedges = emesh.number_of_edges();
const size_t nfaces = emesh.number_of_faces();
Mesh3 mesh;
mesh.reserve(nvertices, nedges, nfaces);
for(EMesh3::Vertex_index vd : emesh.vertices()) {
const EPoint3 vertex = emesh.point(vd);
const double x = CGAL::to_double<EK::FT>(vertex.x());
const double y = CGAL::to_double<EK::FT>(vertex.y());
const double z = CGAL::to_double<EK::FT>(vertex.z());
mesh.add_vertex(Point3(x, y ,z));
}
for(EMesh3::Face_index fd : emesh.faces()) {
std::vector<int> face;
for(EMesh3::Vertex_index vd : vertices_around_face(emesh.halfedge(fd), emesh)) {
face.push_back(vd);
}
mesh.add_face(
CGAL::SM_Vertex_index(face[0]),
CGAL::SM_Vertex_index(face[1]),
CGAL::SM_Vertex_index(face[2])
);
}
return mesh;
}
| You can either create a new mesh like you did but with the function copy_face_graph() or you can use the vertex_property_map() parameter of PMP functions to have one mesh with different point map (exact and inexact).
|
72,585,873 | 72,586,016 | Constructability of trivial types | In regards to C++17; GCC, Clang, and MSVC consider a trival class type not to be constructible by any of its data member types. Since C++20, GCC and MSVC changed this, allowing the example below to compile.
#include <type_traits>
struct t {
int a;
};
static_assert(std::is_constructible<t, int>{});
Unfortunately, Clang seems to disagree and rejects this code when compiling with -std=c++20 as well. Is this a compiler bug of Clang? And why do all compilers not consider a type like t to be constructible with an int when compiling with -std=c++17? After all, t{0} seems to be pretty constructible that way.
| Constructibility is based on the ability to use constructor syntax (T(values)). In C++20, aggregates can be initialized using constructor syntax, but in C++17 and before, they must use {} syntax.
Clang's C++20 implementation is simply not up to the standard yet.
|
72,585,937 | 72,586,000 | Create a `map` using `unique_ptr` | I originally had a problem creating a map of classes, with some help
I realized I actually need a map<string, unique_ptr<myclass>>.
To be more precise:
I have a bunch of specialized classes with a common ancestor.
specialized classes are actually specialized from the same template.
I have a std::map<std::string, unique_ptr<ancestor>> taking ownership
of my instances (I hope).
I need ownership because the function creating the instances is in a
completely different section of code than the place using them.
If useful: I create the map at initialization time and then I only
reference it at runtime; for all practical purposes after initializing
it (a complex affair, involving reading config files) it could become
const.
A minimal example of what I need to achieve is:
#include <iostream>
#include <string>
#include <memory>
#include <map>
class generic {
std::string _name;
public:
generic(std::string name) : _name(name) {}
virtual ~generic() = default;
virtual std::string name() { return _name; }
virtual std::string value() { return "no value in generic"; }
};
template <class T> class special : public generic {
T _value;
public:
special(std::string name, T value) : generic(name), _value(value) {}
virtual ~special() = default;
std::string value() override { return std::to_string(_value); }
};
template <typename T> void add_item(std::map <std::string, std::unique_ptr<generic>> &m, const std::string &n, const T &v) {
m[n] = std::make_unique<special<T>>(typeid(v).name(), v);
}
int
main() {
std::map <std::string, std::unique_ptr<generic>> instances;
add_item<int>(instances, "int", 1);
add_item<bool>(instances, "bool", true);
add_item<float>(instances, "float", 3.1415);
for (auto i : instances) {
std::cout << i.first << " -- " << i.second.get()->name() << " -- " << i.second.get()->value() << std::endl;
}
return 0;
}
Unfortunately I seem to be missing something because compilation bombs with "error: use of deleted function".
Can someone be so kind to help me sort this out?
| In this loop you try to copy unique_ptrs, but the unique_ptr copy constructor is deleted.
for (auto i : instances) {
You need to take them by reference instead:
for (auto& i : instances) {
|
72,586,393 | 72,586,483 | Tribonacci number program doesnt return false | For each number read from the standard input the program should print YES if it is a Tribonacci number and NO otherwise. What am I doing wrong in my program, it prints YES, but it wont print NO when the number is not a tribonacci number. For example when number is 45, it should print no.
Tribonacci number formula
T0=0
T1=1
T2=2
Tn=Tn-1 + Tn-2 + Tn-3 (for n>2)
using namespace std;
bool isTrib(int n) {
if(n==0 || n == 1 || n == 2) {
return true;
}
if(n > 2) {
int trib = isTrib(n-1)+isTrib(n-2)+isTrib(n-3);
if(trib == n) {
return true;
}
}
return false;
}
int main()
{
int n;
while(cin>>n) {
bool result = isTrib(n);
cout << result;
result == 1 ? cout << "YES" << endl : cout << "NO" << endl;
}
return 0;
}
| you're mixing two things: actual tribonacci numbers and "true"/"false" answer to question "whether N is tribonacci", for example variable trib in your code can be either 0, 1, 2 or 3, it cannot take any other values, but you're trying to compare it with real number, which is apples to oranges
here is fixed version:
bool isTrib(int n) {
if(n==0 || n == 1 || n == 2) {
return true;
}
int n1 = 0;
int n2 = 1;
int n3 = 2;
int trib = n1 + n2 + n3;
while (trib <= n) {
if (trib == n) return true;
n1 = n2;
n2 = n3;
n3 = trib;
trib = n1 + n2 + n3;
}
return false;
}
int main()
{
int n;
while(cin>>n) {
bool result = isTrib(n);
cout << (result ? "YES" : "NO") << endl;
}
return 0;
}
|
72,586,974 | 72,587,460 | Building FLTK Project with CMAKE/CONAN | I'm fairly new to C++ / CMake, but I'd like to create a project with FLTK using CMAKE and CONAN as package manager. I'm using Windows 11, but trying to get it to run under WSL (Ubuntu 20.04). My WSL-version supports GUI applications.
When I install everything without Conan and compile the official "fltk-hello-world" from the command line using fltk-config, everything works okay. However, when I try to set it up using Conan und Cmake I get following errors:
/usr/bin/ld: /home/bfl/.conan/data/fltk/1.3.8/_/_/package/b6898709771003e31b8ea824ee836cf119580bd8/lib/libfltk.a(fl_font.cxx.o): in function `Fl_Font_Descriptor::Fl_Font_Descriptor(char const*, int, int)':
fl_font.cxx:(.text+0x232): undefined reference to `XftFontOpenXlfd'
/usr/bin/ld: fl_font.cxx:(.text+0x47e): undefined reference to `XftFontMatch'
/usr/bin/ld: fl_font.cxx:(.text+0x48f): undefined reference to `XftFontOpenPattern'
/usr/bin/ld: fl_font.cxx:(.text+0x4e1): undefined reference to `XftFontOpen'
/usr/bin/ld: /home/bfl/.conan/data/fltk/1.3.8/_/_/package/b6898709771003e31b8ea824ee836cf119580bd8/lib/libfltk.a(fl_font.cxx.o): in function `Fl_Xlib_Graphics_Driver::width(char const*, int)':
fl_font.cxx:(.text+0x954): undefined reference to `XftTextExtents32'
/usr/bin/ld: /home/bfl/.conan/data/fltk/1.3.8/_/_/package/b6898709771003e31b8ea824ee836cf119580bd8/lib/libfltk.a(fl_font.cxx.o): in function `Fl_Xlib_Graphics_Driver::width(unsigned int)':
fl_font.cxx:(.text+0xa5e): undefined reference to `XftTextExtents32'
/usr/bin/ld: /home/bfl/.conan/data/fltk/1.3.8/_/_/package/b6898709771003e31b8ea824ee836cf119580bd8/lib/libfltk.a(fl_font.cxx.o): in function `Fl_Xlib_Graphics_Driver::text_extents(char const*, int, int&, int&, int&, int&)':
fl_font.cxx:(.text+0xb07): undefined reference to `XftTextExtents32'
/usr/bin/ld: /home/bfl/.conan/data/fltk/1.3.8/_/_/package/b6898709771003e31b8ea824ee836cf119580bd8/lib/libfltk.a(fl_font.cxx.o): in function `Fl_Xlib_Graphics_Driver::draw(char const*, int, int, int)':
fl_font.cxx:(.text+0x1140): undefined reference to `XftDrawChange'
/usr/bin/ld: fl_font.cxx:(.text+0x1176): undefined reference to `XftDrawSetClip'
/usr/bin/ld: fl_font.cxx:(.text+0x1209): undefined reference to `XftDrawString32'
/usr/bin/ld: fl_font.cxx:(.text+0x12d9): undefined reference to `XftDrawCreate'
/usr/bin/ld: /home/bfl/.conan/data/fltk/1.3.8/_/_/package/b6898709771003e31b8ea824ee836cf119580bd8/lib/libfltk.a(fl_font.cxx.o): in function `Fl_Xlib_Graphics_Driver::rtl_draw(char const*, int, int, int)':
fl_font.cxx:(.text+0x149b): undefined reference to `XftTextExtents32'
/usr/bin/ld: fl_font.cxx:(.text+0x14cc): undefined reference to `XftDrawChange'
/usr/bin/ld: fl_font.cxx:(.text+0x1502): undefined reference to `XftDrawSetClip'
/usr/bin/ld: fl_font.cxx:(.text+0x1595): undefined reference to `XftDrawString32'
/usr/bin/ld: fl_font.cxx:(.text+0x15f9): undefined reference to `XftDrawCreate'
/usr/bin/ld: /home/bfl/.conan/data/fltk/1.3.8/_/_/package/b6898709771003e31b8ea824ee836cf119580bd8/lib/libfltk.a(fl_font.cxx.o): in function `fl_destroy_xft_draw(unsigned long)':
fl_font.cxx:(.text+0x10d9): undefined reference to `XftDrawChange'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/hello.dir/build.make:84: bin/hello] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/hello.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
So I assume that i am probably not linking XFT? But I am not sure how to do that, do I need to include the correct name in target-link-libraries? My Cmake-File looks like this:
cmake_minimum_required(VERSION 3.2.3)
project(Hello VERSION 0.1.0)
set(EXECUTABLE_NAME hello)
set(EXE_SOURCES hello.cc)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
add_executable(${EXECUTABLE_NAME} ${EXE_SOURCES})
target_include_directories(hello PUBLIC ${FLTK_INCLUDE_DIRS})
target_link_libraries(hello
${CONAN_LIBS})
I'm grateful for any suggestion.
Thanks,
GB
| The conan recipe for fltk does not correctly deal with the cmake system of fltk.
Fltk auto-detects if the system it compiles on has Xft. If it does, then it enables the HAS_XFT variable and compiles some code into the library that uses it.
Conan does not pick up on this and doesn't add Xft to the dependent libraries.
The easiest way around this bug is to manually add the xft dependency.
If you have libXft installed on your system you can simply add an entry of Xft to the target_link_libraries of the target that uses fltk.
Like this:
target_link_libraries(hello ${CONAN_LIBS} Xft)
|
72,587,313 | 72,587,874 | Generate header only library in c++ that output a single hpp file | I want to write a small library in c++ then "compile" it and release it as a single .hpp file. I can't figure out an easy way to create a single .hpp file from a code base though.
I'm attempting to make something similar to catch.hpp. When I look at their code base they seem to be doing something similar. They seem to have a large collection of .h and .cpp files that are then used to generate a .hpp file.
I want my project structure to look something like the following:\
folder
- src
- something.h
- something.cpp
- another_thing.h
- another_thing.cpp
- tests
- something_tests.cpp
- another_thing_tests.cpp
- console_app
- main.cpp
I'd like to create a makefile and run a few commands:
make library => creates library.hpp containing everything in the src folder.
make tests => runs tests
make console => creates library.hpp, then compiles main.cpp in console_app folder
I generally know how to do the make tests, however I don;t understand how to create an hpp file from the src folder.
| @UnholySheep's answer above:
catch.hpp is generated via a script: github.com/log4cplus/Catch/blob/… which essentially just concatenates all the files together into a single file
Paired with @fabian's answer:
Don't even get started with adding .cpp files into your header only lib. There are things usually in cpp files that must not be done in a header only lib, such as non-inline function definitions, ect that can easily result in a name conflict, if your lib is included in more than one translation unit of binary using it. Furthermore I don't see how throwing everything into a single header file is beneficial; this just makes it harder to near impossible to find stuff: noone wants to search your 50k loc file for the stuff they're looking for..
I've determined the best solution is to write the code in .hpp files to begin with. Then just to write a script that concatenates all of the .hpp files into a single file. The file structure will look like this:
folder
- src
- something.hpp
- another_thing.hpp
- tests
- something_tests.cpp
- another_thing_tests.cpp
- console_app
- main.cpp
- library_gen_script.sh
Then the script library_gen_script.sh will just contain logic to package all of the stuff in the src folder into a single .hpp file.
|
72,587,590 | 72,587,639 | How to get started with C++ unit tests | I am just starting with c++ unit testing. I want to create simple tests (without using any framework) using assert commands. How can I start with that?
Should I make different functions for tests and call them in the main in a single file or should I make separate file for each test?
| Just use it like assert(<output-to-test>==<expected-value>)
#include <cassert>
int square(int x){return x*x}
void test1(){
assert(square(1)==1)
assert(square(2)==4)
}
void main(){test1();}
|
72,587,811 | 72,587,875 | Consecutive lines printing same pointer with "std::cout" produce completely different output | I apologize for the vague title of my question. I don't know a better way to phrase it. I've never asked a Stack Overflow question before but this one has me completely stumped.
A method in class Chunk uses the Eigen linear algebra library to produce a vector3f, which is then mapped to a C-style array with the following.
ColPivHouseholderQR<MatrixXf> dec(f);
Vector3f x = dec.solve(b);
float *fit = x.data();
return fit;
This array is returned and accessed in the main function. However, whenever I attempt to print out a value from the pointer, I get completely different results. A sample is below.
Chunk test = Chunk(CHUNK_SIZE, 0, 0, 1, poBand);
float* fit = test.vector; // Should have size 3
std::cout << fit[0] << std::endl; // Outputs 3.05 (correct)
std::cout << fit[0] << std::endl; // Outputs 5.395e-43
std::cout << fit[0] << std::endl; // Outputs 3.81993e+08
What makes this issue even more perplexing is that the incorrect values change when I end the lines with "\n" or ", ". The first value is always the expected value, no matter whether I print index 0, 1, or 2.
I have tried dynamically allocating memory for the fit variable, as well as implementing the code on this answer, but none of it changes this functionality.
Thank you in advance for any guidance on this issue.
Minimally Reproducible Example:
float* getVector() {
Eigen::Vector3f x;
x << 3, 5, 9;
float* fit = x.data();
return fit;
}
int main(void) {
float* fit = getVector();
std::cout << fit[0] << std::endl;
std::cout << fit[0] << std::endl;
std::cout << fit[0] << std::endl;
}
| You create the vector x in the function on the stack. It is destroyed after the function exited. Hence your pointer is invalid.
Here an example with shared_ptr
ColPivHouseholderQR<MatrixXf> dec(f);
Vector3f x = dec.solve(b);
shared_ptr<float> fit(new float[3],std::default_delete<float[]>());
memcpy(fit,x.data(),sizeof(float)*3);
return fit;
Another possible way is
ColPivHouseholderQR<MatrixXf> dec(f);
Vector3f x = dec.solve(b);
return x;
|
72,587,926 | 72,587,988 | Datatype for vector<vector<int> > not matching | So, in the following piece of code i am calculating the exponent of a matrix. Here,
long long mod = (1e+9)+7;
vector<vector<int>> matrixMultiply(vector<vector<int>>& A, vector<vector<int>>& B){
vector<vector<int>> ans(2, vector<int> (2));
for(int i = 0; i < 2; ++i)
for(int j = 0; j < 2; ++j)
for(int k = 0; k < 2; ++k){
ans[i][j] += ((A[i][k]%mod) * (A[k][j]%mod))%mod;
ans[i][j] = ans[i][j]%mod;
}
return ans;
}
vector<vector<int>> matrixPower(int n, vector<vector<int>>& M){
if(n==1) {
return M;
}
vector<vector<int>> temp = matrixPower(n/2,M);
if(n%2==0){
return matrixMultiply(temp,temp);
}
else{
return matrixMultiply(matrixMultiply(temp,temp),M);
}
}
int solve(int A){
vector< vector<int>> M{{1,1},{1,0}};
vector< vector<int>> Mpower = matrixPower(A-1,M);
return Mpower[0][0];
}
int main(){
cout << solve(4);
return 0;
}
Here when i run the code, I get the following error,
main.cpp: In function 'std::vector<std::vector<int> > matrixPower(int,
std::vector<std::vector<int> >&)': main.cpp:41:49: error: invalid initialization of non-const
reference of type 'std::vector<std::vector<int> >&' from an rvalue of type
'std::vector<std::vector<int> >' return matrixMultiply(matrixMultiply(temp,temp),M);
~~~~~~~~~~~~~~^~~~~~~~~~~
main.cpp:21:25: note: initializing argument 1 of 'std::vector<std::vector<int> >
matrixMultiply(std::vector<std::vector<int> >&, std::vector<std::vector<int> >&)'
vector<vector<int>> matrixMultiply(vector<vector<int>>& A, vector<vector<int>>& B){
^~~~~~~~~~~~~~
However when I do little bit of modification in my matrixPower function, like this,
vector<vector<int>> matrixPower(int n, vector<vector<int>>& M){
if(n==1) {
return M;
}
vector<vector<int>> temp = matrixPower(n/2,M);
vector<vector<int>> multiplied_matrix = matrixMultiply(temp,temp);
if(n%2==0){
return multiplied_matrix;
}
else{
return matrixMultiply(multiplied_matrix,M);
}
}
It works without any compilation error.
Please help me understood what exactly is the difference between this two pieces of code.
Thank you.
| The parameters of matrixMultiply are of type vector<vector<int>>& - i.e. "reference to vector of vector of int". (The & means reference.)
This means that instead of the compiler making a copy of the matrix, and giving that copy to matrixMultiply to use, it instead just gives it a reference (basically just the memory address) to the existing copy that the caller already has.
However, in your first example, the caller doesn't actually store the matrix returned by the first matrixMultiply call anywhere, it just passes it straight to the second matrixMultiply call. This is known as a temporary object, and can't be passed as a non-const reference.
If you want the efficiency of passing by reference, without having to create the multiplied_matrix variable, you could change matrixMultiply to take const references instead - i.e. vector<vector<int>> const&. This means that matrixMultiply can't modify the original matrices, but it can still use the data in them to create a new (multiplied) matrix. In this case you would not need to make any changes to the body of matrixMultiply to allow it to work with const references.
So why can you pass a temporary object to a const reference? Well, if the callee were allowed to modify the referenced object, where would those modifications go? There's no actual variable in the caller's scope where that object "lives", so clearly the caller doesn't expect to receive information back from the callee through the reference.
Ok, but what if the caller wants to modify the parameter for its own purposes (e.g. because it wants to make some changes to the parameter, and doesn't want to have to copy it)? Well, that's where "move semantics" come in. This gets a bit more complicated though, so you may just want to use a const reference for now, and then if your function needs to take a copy of the referenced object, it can do that explicitly.
Here are some links for more info on temporary objects and move semantics:
https://learn.microsoft.com/en-us/cpp/cpp/temporary-objects?view=msvc-170
Temporary objects - when are they created, how do you recognise them in code?
What is move semantics?
|
72,588,075 | 72,588,141 | for loop not taking any floating point variables | I have this problem, where I can input "2 10 8" and it will output "8", but I want to be able to input "2 -25.2 -38.4". This immediately crashes the for loop and the program displays "-25.0" instead of "-25.2", effectively deleting the number in the decimal place.
Is there anyone that can help?
int main() {
int numVals;
static_cast<double>(numVals);
double minVal;
int i;
int iteration;
cin >> iteration;
for (i = 0; i < iteration; ++i) {
cin >> numVals;
numVals = numVals * 10; //program completely ignores this...
if (i == 0) {
minVal = numVals;
}
else if (numVals < minVal) {
minVal = numVals;
}
}
cout << fixed << setprecision(1) << minVal / 10 << endl;
return 0;
}
| You are trying to read -25.2 to a numVals variable of type int. It reads -25 to numVals, but then tries to read .2 next time, which is not a valid integer. When you tried this, the input stream variable cin goes to a failure state, and doesn't take any more input.
Change numVals from type int to double:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double numVals;
double minVal;
int i;
int iteration;
cin >> iteration;
for (i = 0; i < iteration; ++i)
{
cin >> numVals;
numVals = numVals * 10;
if (i == 0)
{
minVal = numVals;
}
else if (numVals < minVal)
{
minVal = numVals;
}
}
cout << fixed << setprecision(1) << minVal / 10 << endl;
return 0;
}
|
72,588,289 | 72,588,324 | Why do variadic templates fail to find an appropriate constructor? | If you look at main you'll see I can call write with 4, t2 (or t) but not both in the same call, why? Is there anything I can do outside of breaking them up into seperate calls?
template<class T>
struct Test
{
T data;
constexpr Test()=default;
Test(Test&)=delete;
void Write() { }
template<typename...Args>
void Write(unsigned int v, Args...args) {
Write(args...);
}
template<typename...Args>
void Write(int v, Args...args) {
Write(args...);
}
template<typename...Args>
void Write(char v, Args...args) {
Write(args...);
}
template<typename...Args>
void Write(const Test<char>&v, Args...args) { Write(args...); }
};
int main()
{
Test<char> t;
const Test<char>&t2=t;
t.Write(4); //ok
t.Write(t2);//ok
t.Write(0, t2); //not ok
}
| As you've deleted the copy-constructor the last line will not work. One way to fix it is passing the variadic args as reference like:
#include <iostream>
template<class T>
struct Test
{
T data;
constexpr Test()=default;
Test(Test&)=delete;
void Write() { }
template<typename...Args>
void Write(unsigned int v, Args&...args) {
Write(args...);
}
template<typename...Args>
void Write(int v, Args&...args) {
Write(args...);
}
template<typename...Args>
void Write(char v, Args&...args) {
Write(args...);
}
template<typename...Args>
void Write(const Test<char>&v, Args&...args) { Write(args...); }
};
int main()
{
Test<char> t;
const Test<char>&t2=t;
t.Write(4); //ok
t.Write(t2);//ok
t.Write(0, t2); //ok
}
|
72,588,408 | 72,778,459 | vcpkg how to edit package file when compilation fails when installing package? | I'm installing dependencies for some project which downloads dependencies with vcpkg (the project is Hyperledger Iroha, but it does not matter). Unfortunately when compiling dependencies with my compiler (g++ 12.1.0) one of packages (abseil) is not compiling.
The reason why it is not compiling is easy to fix in code - just one line to change.
The line is pointed by cmake:
CMake Error at scripts/cmake/vcpkg_execute_build_process.cmake:146 (message):
Command failed: /usr/bin/cmake --build . --config Debug --target install -- -v -j13
Working Directory: /home/agh/Pulpit/blockchain/internship2022/iroha/vcpkg-build/buildtrees/abseil/x64-linux-dbg
See logs for more information:
/home/agh/Pulpit/blockchain/internship2022/iroha/vcpkg-build/buildtrees/abseil/install-x64-linux-dbg-out.log
and the error is:
/home/agh/Pulpit/blockchain/internship2022/iroha/vcpkg-build/buildtrees/abseil/src/ca9688e9f6-e4cda1d679.clean/absl/debugging/failure_signal_handler.cc:139:32: error: no matching function for call to ‘max(long int, int)’
139 | size_t stack_size = (std::max(SIGSTKSZ, 65536) + page_mask) & ~page_mask;
| ~~~~~~~~^~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/12.1.0/algorithm:60,
The reason is easy to fix - I just need to change one line to fix this.
Unfortunately when I'm changing the line of code and then after rerunning:
vcpkg install abseil
my changes are being removed before compilation. I found option which should help:
--editable, but it is happening again.
I would like to ask what is more professional (but still fast) way to change files, which are being build with vcpkg and containing errors?
The one solution which I found is that I can edit package:
-- Using cached /home/agh/Pulpit/blockchain/internship2022/iroha/vcpkg-build/downloads/abseil-abseil-cpp-997aaf3a28308eba1b9156aa35ab7bca9688e9f6.tar.gz
when I edit the package I see error:
File path: [ /home/agh/Pulpit/blockchain/internship2022/iroha/vcpkg-build/downloads/abseil-abseil-cpp-997aaf3a28308eba1b9156aa35ab7bca9688e9f6.tar.gz ]
Expected hash: [ bdd80a2278eef121e8837791fdebca06e87bfff4adc438c123e0ce11efc42a8bd461edcbbe18c0eee05be2cd6100f9acf8eab3db58ac73322b5852e6ffe7c85b ]
Actual hash: [ cf8bb1676d2fcba8bdd4bc30e2060bc5552a348d6e192561aec2763460120b10dcb86e29efe60d972d4b241783563bc8067381c48209daee4ecc429786ef6bba ]
so I can edit file containing the hash: ports/abseil/portfile.cmake
Another solution is to run proper cmake of the abseil project with VERBOSE=1, then copy failing build commands after that edit files and rerun commands.
I know that my solutions are quite dirty so I would like to know if there is cleaner way to solve problem - how to edit source code of a library when it is not compiling when we use vcpkg package manager?
| This is how I do it:
Run install with --editable
vcpkg install abseil --editable
Initialize git repo in source dir:
cd buildtrees/abseil/src/_random_string_/
git init .
git add .
git commit -m "init"
Patch the library
Verify the library builds by calling install with --editable again
vcpkg install abseil --editable
Create patch from changes (or commits)
git diff > fix_build.patch
Copy patch into port dir and adjust portfile.cmake
vcpkg_from_github(
REPO google/abseil
...
PATCHES fix_build.patch # <-- this is our patch
)
Copy the port directory into your project's overlay-ports dir. -OR- Update port version, submit it into your custom registry.
(optional, but appreciated) Create PR in upstream and vcpkg main repo.
|
72,588,604 | 72,597,786 | A 'for' loop that looks at numbers and assigns them a Boolean statement it can compare several inputs | Would someone please look at the below code and see why it works most of the time but not always?
It works when I input something like "7 1000 1002 896 897 1004 987 960", it shows Unallowed value(s) like it's supposed to.
But if I input "7 896 1003 1004 899 897 898 906", it should say Unallowed value(s), but it works periodically.
int main() {
int inputCount;
bool allAllowed;
int range;
cin >> inputCount;
cin >> range;
if ((range >= 900) && (range <= 1000)) {
allAllowed = 0;
for (int i = 1; i < inputCount; ++i) {
cin >> range;
if ((range >= 900) && (range <= 1000)) {
allAllowed = 0;
}
else if ((range < 900) || (range > 1000)) {
// i = inputCount + 1;
allAllowed = 1;
}
}
}
else if ((range < 900) || (range > 1000)) {
allAllowed = 1;
}
if (allAllowed) {
cout << "Only allowed values" << endl;
}
else {
cout << "Unallowed value(s)" << endl;
}
return 0;
}
| Your initial value of range, 896, isn't between 900 and 1000 and satisfies the condition
else if ((range < 900) || (range > 1000)), making allAllowed = 1,
meaning it will always return "Only allowed values".
Something else you should consider is that your program will only consider the last inputted number to determine allAllowed within the condition if ((range >= 900) && (range <= 1000))
|
72,588,650 | 72,588,689 | C++ long double precision difference with and without using namespace std; | I have stumbled upon quirky C++ behavior that I cannot explain.
I am trying to calculate the dimensions of an image when resizing it (maintaining its ratio) to fit as much screen as possible. The x, y variables are dimensions of the image and X, Y variables are dimensions of the screen. When the resulting dimensions are not integers, I need to round them using standard rules of mathematics.
This program for inputs 499999999999999999 10 1000000000000000000 19 gives the (incorrect) answer of 950000000000000000 19.
#include <iostream>
#include <cmath>
#include <algorithm>
int main()
{
long long x, y, X, Y;
std::cin >> x >> y >> X >> Y;
long double ratio = std::min((long double)X/x, (long double)Y/y);
x = round(ratio*x);
y = round(ratio*y);
std::cout << x << " " << y << std::endl;
return 0;
}
However, code below (only change is using namespace std; and removing std:: from main function body) gives the correct answer of 949999999999999998 19.
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
long long x, y, X, Y;
cin >> x >> y >> X >> Y;
long double ratio = min((long double)X/x, (long double)Y/y);
x = round(ratio*x);
y = round(ratio*y);
cout << x << " " << y << endl;
return 0;
}
I am using g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0 and compiling the program with g++ -std=c++17 -Wall -Wextra -Wshadow.
| In the first case you are calling double round(double) function from the global namespace, which is pulled in by the cmath header.
In the second case you are calling overloaded long double std::round(long double) function from the std namespace since your are using namespace std.
You can fix your code by adding std:: in front of round, as in:
#include <iostream>
#include <cmath>
#include <algorithm>
int main()
{
long long x, y, X, Y;
std::cin >> x >> y >> X >> Y;
auto ratio = std::min((long double)X / x, (long double)Y / y);
x = std::round(ratio * x); // <-- add std:: here
y = std::round(ratio * y); // <-- add std:: here
std::cout << x << " " << y;
return 0;
}
UPDATE:
To explain what's going on here, when you call round in the first case, ratio * x is implicitly converted to double (which can only store 15 significant digits) before it is passed to the function.
This leads to loss of precision and an unexpected result in your case. No quirks.
|
72,588,866 | 72,589,118 | How to save XmlTextReader strings inside a variable or vector in C++/CLI? | I am currently working on a project in which I have to receive a XML file and sort one of the elements.
Before actually getting to the sorting part, I have to parse the XML file, so I am using XmlTextReader, which is working well. However, I need to save each element's attribute in a variable or in a vector to be able to perform the sort afterwards (my struggle is with trying to store the reader->Value).
Here is part of my code, any ideas?
P.S. You can see my struggle in the second switch case below, I kept receiving errors on all those attempts.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <tchar.h>
#using <System.Windows.Forms.dll>
#using <mscorlib.dll>
using namespace std;
using namespace System;
using namespace System::Xml;
int main() {
string myText = "";
vector<string> entries = { "DeTal" };
entries.insert(entries.end(), "Fulano");//test purposes
XmlTextReader^ reader = gcnew XmlTextReader("C:\\Users...");
while (reader->Read())
{
switch (reader->NodeType)
{
case XmlNodeType::Element: // The node is an element.
Console::Write("<{0}", reader->ReadToFollowing("TITLE"));
while (reader->MoveToNextAttribute()) {// Read the attributes.
Console::Write(" {0}='{1}'", reader->GetAttribute("TITLE"));
}
Console::WriteLine(">");
break;
case XmlNodeType::Text: //Display the text in each element.
Console::WriteLine(reader->Value); //reads the actual element content
//entries.insert(entries.end(), reader->Value);
//entries.push_back(reader->Value);
//myText = Console::WriteLine(reader->Value);
//myText = Console::WriteLine(reader->ReadString());
//myText = reader->Value;
break;
case XmlNodeType::EndElement: //Display the end of the element.
Console::Write("</{0}", reader->Name);
Console::WriteLine(">");
break;
}
}
cout << "\nPress enter to start sort: ";
Console::ReadLine();
| reader->Value is a .NET System::String (a 16bit Unicode string).
You are trying to assign it to, and store it in a std::vector of, std::string (an 8bit string).
Those two string types are not directly compatible with each other, which is why you are having troubles.
You need to either:
change your myText variable to System::String, and your entries vector to hold System::String elements.
convert the System::String data to std::string. How to do that is documented on MSDN: How to: Convert System::String to Standard String. Also see How to turn System::String^ into std::string? on StackOverflow.
|
72,588,919 | 72,588,970 | Abstract class selectively expose methods based on derived type | I am writing an program that implements a factory TimeManager to generate two types of objects; a Timer and a StopWatch. Both of these objects are derived from an abstract class TimePiece, and share common methods. I would like the factory to return type TimePiece, but because Timer implements extra methods, I cant. How can I make TimePiece expose Timer's extra methods without exposing them to StopWatch when those respective types are created? I hope this makes sense, as it is a little hard to explain.
TimeManager.h
enum TimePieceType{TIMER, STOP_WATCH};
class TimeManager {
public:
TimeManager();
~TimeManager();
void Tick();
TimePiece* AddTimePiece(TimePieceType timeType);
};
TimePiece.h
enum RunningState { STOPPED, RUNNING, PAUSED };
class TimePiece {
private:
unsigned long startTime = 0;
unsigned long currentTime = 0;
unsigned long pauseOffset = 0;
protected:
Time time;
RunningState state = STOPPED;
public:
TimePiece() = default;
virtual ~TimePiece() = default;
void Stop();
void Start();
void Pause();
void Resume();
void Reset();
virtual void Tick();
Time GetTime();
RunningState GetState();
virtual uint8_t GetId() = 0;
};
StopWatch.h
class StopWatch : public TimePiece {
private:
uint8_t watchId = 0;
static int8_t currentId;
public:
StopWatch();
virtual ~StopWatch();
uint8_t GetId();
};
Timer.h
class Timer : public TimePiece {
private:
uint8_t timerId = 0;
static int8_t currentId;
unsigned long timeout;
public:
Timer();
~Timer();
void Tick() override;
void SetTimeoutMs(unsigned long timeout);
void SetTimeoutSec(unsigned long timeout);
uint8_t GetId();
Time GetRemainingTime();
unsigned long GetTimeout();
};
| You should not return TimePiece* because the two subclasses are sharing TimePiece for its implementation, not for its interface.
A simple approach is to give TimeManager two separate methods:
Timer* AddTimer();
StopWatch* AddStopWatch();
You can exploit polymorphic behavior if you need the Remove method:
void RemoveTimePiece(TimePiece*);
|
72,588,971 | 72,589,063 | vector push_back add new items | I need add items to a vector who are created as std::vector<char*> Lista;
then i do:
char txt[10];
for (int x = 0; x <= 5; x++)
{
sprintf(txt, "num%d", x);
printf("Add %s\n", txt);
Lista.push_back(txt);
}
but if i loop Lista items it show show:
for (int x = 0; x <= Lista.size() - 1; x++)
{
printf("Items > [%d] %s\n", x, Lista[x]);
}
Items > [0] num5
Items > [1] num5
Items > [2] num5
Items > [3] num5
Items > [4] num5
Items > [5] num5
what i'm doing wrong? i need use char* not string.
| You're pushing five pointers to the same array into your vector, so when you print the contents of the array pointed to by each pointer they're all the same.
You only have a single array: txt. Each time through your loop, you write new contents into that array and push a pointer to it into Lista. So the first time through your loop you have this:
txt
┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬─────┬─────┬─────┐
│ │ │ │ │ │ │ │ │ │ │
│ 'n' │ 'u' │ 'm' │ '0' │ '\0' │ ? │ ? │ ? │ ? │ ? │
│ │ │ │ │ │ │ │ │ │ │
└─────┴─────┴─────┴─────┴──────┴─────┴─────┴─────┴─────┴─────┘
▲
│
└───┐
│
┌───┼───┐
│ │ │
│ │ │
│ │
└───────┘
Lista
Then the second time through you modify txt and add another pointer to it to Lista, so you have this:
txt
┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬─────┬─────┬─────┐
│ │ │ │ │ │ │ │ │ │ │
│ 'n' │ 'u' │ 'm' │ '1' │ '\0' │ ? │ ? │ ? │ ? │ ? │
│ │ │ │ │ │ │ │ │ │ │
└─────┴─────┴─────┴─────┴──────┴─────┴─────┴─────┴─────┴─────┘
▲ ▲
│ └─────────┐
└───┐ │
│ │
┌───┼───┬───┼───┐
│ │ │ │ │
│ │ │ │ │
│ │ │
└───────┴───────┘
Lista
And so on. Every element of Lista contains a pointer to the same array, which you modify in each iteration of your loop. When you go back and print the contents of the array pointed to by each element of Lista, they all point to the same array, so the same thing gets printed for each.
If you want to store different text in each element of Lista, you will need to create a separate string for each. The easiest way to do that would be to change the type of Lista to std::vector<std::string> and let the std::string class handle allocating space for each string:
for (int x = 0; x <= 5; ++x) {
std::string text = std::format(num{}, x); // Use std::ostringstream or sprintf if your compiler doesn't support std::format
Lista.push_back(text);
}
Then you can use std::string's data member function to get a pointer to the string's underlying char* if you need to pass it to some interface that doesn't support std::string. Keep in mind that the lifetime of the arrays pointed to by those pointers are tied to the lifetime of the std::string object, so be careful not to use them after the std::string (or the std::vector that contains it) goes out of scope.
If you absolutely do not want to use std::string to manage the lifetime of your arrays, you can allocate them yourself with new[], just remember that you must then remember to delete[] them when you're done with them to avoid leaking memory:
for (int x = 0; x <= 5; ++x) {
char* txt = new char[5];
sprintf(txt, "num%d", x);
Lista.push_back(txt);
}
// ... stuff
for (char* txt : Lista) {
delete[] txt;
}
There are very few legitimate reasons to do this though. In 99.9% of cases you should use std::string or some sort of smart pointer to manage your memory.
Note: Your program also exhibits undefined behavior because you access your array out of bounds with Lista[x+1] = txt; you should get rid of that line.
|
72,588,979 | 72,591,682 | nppi resize function with 3 channels getting strange output | I'm getting a strange error when using nppi geometry transform functions from nppi cuda libraries. The code is here:
#include <nppi.h>
#include <nppi_geometry_transforms.h>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <vector>
void write(const cv::Mat &mat1, const std::string &path) {
auto mat2 = cv::Mat(mat1.rows, mat1.cols, CV_8UC4);
for (int i = 0; i < mat1.rows; i++) {
for (int j = 0; j < mat1.cols; j++) {
auto &bgra = mat2.at<cv::Vec4b>(i, j);
auto &rgb = mat1.at<cv::Vec3b>(i, j);
bgra[0] = rgb[2];
bgra[1] = rgb[1];
bgra[2] = rgb[0];
bgra[3] = UCHAR_MAX;
}
}
std::vector<int> compression_params;
compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
cv::imwrite(path, mat2, compression_params);
}
int main() {
std::cout << "Hello, World!" << std::endl;
auto mat = cv::Mat(256, 256, CV_8UC3);
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
auto &rgb = mat.at<cv::Vec3b>(i, j);
rgb[0] = (uint8_t)j;
rgb[1] = (uint8_t)i;
rgb[2] = (uint8_t)(UCHAR_MAX - j);
}
}
write(mat, "./test.png");
uint8_t *gpuBuffer1;
uint8_t *gpuBuffer2;
cudaMalloc(&gpuBuffer1, mat.total());
cudaMalloc(&gpuBuffer2, mat.total());
cudaMemcpy(gpuBuffer1, mat.data, mat.total(), cudaMemcpyHostToDevice);
auto status = nppiResize_8u_C3R(
gpuBuffer1, mat.cols * 3, {.width = mat.cols, .height = mat.rows},
{.x = 0, .y = 0, .width = mat.cols, .height = mat.rows}, gpuBuffer2,
mat.cols * 3, {.width = mat.cols, .height = mat.rows},
{.x = 0, .y = 0, .width = mat.cols, .height = mat.rows},
NPPI_INTER_NN);
if (status != NPP_SUCCESS) {
std::cerr << "Error executing Resize -- code: " << status << std::endl;
}
auto mat2 = cv::Mat(mat.rows, mat.cols, CV_8UC3);
cudaMemcpy(mat2.data, gpuBuffer2, mat.total(), cudaMemcpyDeviceToHost);
write(mat2, "./test1.png");
}
Basically I display a rainbow picture. Then write it to the GPU then resize it to the EXACT same size, then copy it back to the host then display it again. What I'm getting is garbled data in about 2/3s of the return picture.
First picture is the input picture.
Second input picture is the output picture.
I expect both pictures to be the same.
If I adjust the ROI with offsets and change the width and height for the destination buffer the pixels in the top 1/3 of the resized picture actually moves and resizes correctly. But the rest of the picture is garbled. Not sure what's wrong. Does anyone with experience in cuda nppi libraries or image processing in general have an idea what's going on?
CMake file included below for convenience to anyone who wants to compile it. You have to have opencv and cuda toolkit installed as C++ libs:
cmake_minimum_required(VERSION 3.18)
project(test_nppi)
enable_language(CUDA)
set(CMAKE_CXX_STANDARD 17)
find_package(CUDAToolkit REQUIRED)
find_package(OpenCV)
message(STATUS ${CUDAToolkit_INCLUDE_DIRS})
add_executable(test_nppi main.cu)
target_link_libraries(test_nppi ${OpenCV_LIBS} CUDA::nppig)
target_include_directories(test_nppi PUBLIC ${OpenCV_INCLUDE_DIRS} ${CUDAToolkit_INCLUDE_DIRS})
set_target_properties(test_nppi PROPERTIES
CUDA_SEPARABLE_COMPILATION ON)
I've used the nppi resize function for single channel pictures before and I don't have this issue. The 3 channel nppi resize function is getting weird output and I'm thinking I'm not completely understanding the input parameters. The Step is multiplied by 3 because of 3 color channels, but all other sizes just are measuring the dimensions by pixels; and the sizes of src and destination are the same... not sure what I'm not understanding here.
| The issue is that mat.total() equals the total number of pixels, and not the total number of bytes.
According to OpenCV documentation:
total () const
Returns the total number of array elements.
In you code sample, mat.total() equals 256*256, while total number of bytes equals 256*256*3 (RGB applies 3 bytes per pixel).
(In OpenCV terminology "array element" is equivalent to image pixel).
cudaMemcpy(gpuBuffer1, mat.data, mat.total()... copies only 1/3 of the total image bytes, so only the upper 1/3 of the image data is valid.
According to this post, the correct way for computing the number of bytes is:
size_t mat_size_in_bytes = mat.step[0] * mat.rows;
In most cases for CV_8UC3, mat.step[0] = mat.cols*3, but for covering all the cases, we better use mat.step[0].
Corrected code sample:
#include "nppi.h"
#include "nppi_geometry_transforms.h"
#include <iostream>
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgcodecs.hpp"
#include <vector>
void write(const cv::Mat& mat1, const std::string& path) {
auto mat2 = cv::Mat(mat1.rows, mat1.cols, CV_8UC4);
for (int i = 0; i < mat1.rows; i++) {
for (int j = 0; j < mat1.cols; j++) {
auto& bgra = mat2.at<cv::Vec4b>(i, j);
auto& rgb = mat1.at<cv::Vec3b>(i, j);
bgra[0] = rgb[2];
bgra[1] = rgb[1];
bgra[2] = rgb[0];
bgra[3] = UCHAR_MAX;
}
}
std::vector<int> compression_params;
compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
cv::imwrite(path, mat2, compression_params);
}
int main() {
std::cout << "Hello, World!" << std::endl;
auto mat = cv::Mat(256, 256, CV_8UC3);
auto mat2 = cv::Mat(mat.rows, mat.cols, CV_8UC3);
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
auto& rgb = mat.at<cv::Vec3b>(i, j);
rgb[0] = (uint8_t)j;
rgb[1] = (uint8_t)i;
rgb[2] = (uint8_t)(UCHAR_MAX - j);
}
}
write(mat, "./test.png");
uint8_t* gpuBuffer1;
uint8_t* gpuBuffer2;
size_t mat_size_in_bytes = mat.step[0] * mat.rows; // https://stackoverflow.com/questions/26441072/finding-the-size-in-bytes-of-cvmat
size_t mat2_size_in_bytes = mat2.step[0] * mat2.rows;
cudaMalloc(&gpuBuffer1, mat_size_in_bytes);
cudaMalloc(&gpuBuffer2, mat2_size_in_bytes);
cudaMemcpy(gpuBuffer1, mat.data, mat_size_in_bytes, cudaMemcpyHostToDevice);
NppiSize oSrcSize = { mat.cols, mat.rows };
NppiRect oSrcRectROI = { 0, 0, mat.cols, mat.rows };
NppiSize oDstSize = { mat2.cols, mat2.rows };
NppiRect oDstRectROI = { 0, 0, mat2.cols, mat2.rows };
auto status = nppiResize_8u_C3R(
gpuBuffer1, mat.step[0], oSrcSize,
oSrcRectROI, gpuBuffer2,
mat2.step[0], oDstSize,
oDstRectROI,
NPPI_INTER_NN);
if (status != NPP_SUCCESS) {
std::cerr << "Error executing Resize -- code: " << status << std::endl;
}
cudaMemcpy(mat2.data, gpuBuffer2, mat2_size_in_bytes, cudaMemcpyDeviceToHost);
write(mat2, "./test1.png");
}
Output:
|
72,589,416 | 72,640,109 | about pybind11 Return to the c++ array modification problem question | c++
How to return the xyz array without changing the definition of the Tile structure? You can use the subscript to modify the value
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
struct Tile {
float xyz[3];
};
struct Vector3d
{
float x;
float y;
float z;
Vector3d(float x, float y, float z) {
this->x = x;
this->y = y;
this->z = z;
}
Tile* pTile = 0;
/*
struct *p01 = 0;
struct *p02 = 0;
....
*/
};
PYBIND11_MODULE(bbbb, m)
{
py::class_<Vector3d>(m, "Vector3d")
.def(py::init<float, float, float>())
.def_property("x", [](Vector3d& p)->float {
return p.x;
}, [](Vector3d &p, float x) {
p.x = x;
if (p.pTile)
p.pTile->xyz[0] = x;
});
py::class_<Tile>(m, "Tile")
.def(py::init <>())
.def_property("xyz", [](Tile& p)->py::array {
auto dtype = pybind11::dtype(pybind11::format_descriptor<float>::format());
return pybind11::array(dtype, { 3 }, { sizeof(float) }, p.xyz, nullptr);
}, [](Tile& p) {})
.def_property("vec_xyz", [](Tile& p)->Vector3d {
Vector3d vec(p.xyz[0], p.xyz[1], p.xyz[2]);
vec.pTile = &p;
return vec;
}, [](Tile& p) {})
.def("__repr__", [](const Tile &p) {
char buff[100] = { 0 };
sprintf(buff, "x:%f y:%f z:%f", p.xyz[0], p.xyz[1], p.xyz[2]);
return std::string(buff, strlen(buff));;
});
}
python
>>> import bbbb
>>> t = bbbb.Tile()
>>> print(t)
x:0.000000 y:0.000000 z:0.000000
>>> t.xyz[0] = 1.5 #Modifying the value does not work
>>> print(t)
x:0.000000 y:0.000000 z:0.000000
>>> t.vec_xyz.x = 2.5 #Values can be modified
>>> print(t)
x:2.500000 y:0.000000 z:0.000000
>>>
How to make t.xyz[0] = 1.5 work without changing the definition of the Tile structure
If there are multiple similar structures, you need to add structure pointers one by one in Vector3D, which is too troublesome
is there a better way than to return to Vector3D
| c++
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
struct Tile1 { //Assume that the imported library cannot modify the definition
float xyz[3];
};
struct Tile2 { //Assume that the imported library cannot modify the definition
short xyz[6];
};
template<typename TT, typename A, typename B>
struct List {
TT& m_obj;
B TT::*pp;
List(TT& obj, B TT::*pm) : m_obj(obj), pp(pm) {
}
void set(int i, A v) {
if (i >= size()) {
py::pybind11_fail("IndexError: list index out of range");
}
(m_obj.*pp)[i] = v;
}
A get(int i) {
if (i >= size()) {
py::pybind11_fail("IndexError: list index out of range");
}
return (m_obj.*pp)[i];
}
int size() {
return sizeof((m_obj.*pp)) / sizeof((m_obj.*pp)[0]);
}
};
#define LIST_DEFINE(TT,A,B) List<TT, A, A[B]>
#define LIST_DEFINE_TILE1 LIST_DEFINE(Tile1, float, 3)
#define LIST_DEFINE_TILE2 LIST_DEFINE(Tile2, short, 6)
#define LIST_DEFINE_NEW(TT,A,B,M) \
py::class_<LIST_DEFINE(TT,A,B)>(M, "List_"#A"_"#B) \
.def("__getitem__", [](LIST_DEFINE(TT,A,B)& p, int i) { return p.get(i); }) \
.def("__setitem__", [](LIST_DEFINE(TT,A,B)& p, int i, A v) { p.set(i, v); }) \
.def_property_readonly("length", [](LIST_DEFINE(TT,A,B)& p) { return p.size(); })
void init_Tile1(py::module& m) {
py::class_<Tile1>(m, "Tile1")
.def(py::init <>())
.def_property_readonly("xyz", [](Tile1& p) {
return LIST_DEFINE_TILE1(p, &Tile1::xyz);
})
.def("__repr__", [](const Tile1 &p) {
char buff[100] = { 0 };
sprintf(buff, "x:%f y:%f z:%f", p.xyz[0], p.xyz[1], p.xyz[2]);
return std::string(buff, strlen(buff));;
});
LIST_DEFINE_NEW(Tile1, float, 3, m); //List_flost_3
}
void init_Tile2(py::module& m) {
py::class_<Tile2>(m, "Tile2")
.def(py::init <>())
.def_property_readonly("xyz", [](Tile2& p) {
return LIST_DEFINE_TILE2(p, &Tile2::xyz);
})
.def("__repr__", [](const Tile2 &p) {
char buff[100] = { 0 };
sprintf(buff, "ax:%d ay:%d az:%d\nbx:%d by:%d bz:%d",
p.xyz[0], p.xyz[1], p.xyz[2],
p.xyz[3], p.xyz[4], p.xyz[5]);
return std::string(buff, strlen(buff));
});
LIST_DEFINE_NEW(Tile2, short, 6, m); //List_short_6
}
PYBIND11_MODULE(bbbb, m)
{
init_Tile1(m);
init_Tile2(m);
}
python
>>> import bbbb
>>> a = bbbb.Tile1()
>>> a.xyz.length
3
>>> a
x:0.000000 y:0.000000 z:0.000000
>>> a.xyz[1] = 1.5 #Can modify the value and work
>>> a
x:0.000000 y:1.500000 z:0.000000
>>> b = bbbb.Tile2()
>>> b.xyz.length
6
>>> b
ax:0 ay:0 az:0
bx:0 by:0 bz:0
>>> b.xyz[5] = 100 #Can modify the value and work
>>> b
ax:0 ay:0 az:0
bx:0 by:0 bz:100
A few days after I posted the question and no one replied to me, I came up with a temporary solution during this time, but it is still unavoidable that if there are arrays of different types and lengths, you need to define different types of List_type_n to return, by the way Ask if there is a better solution than this
|
72,590,080 | 72,590,112 | C++ STL Map : Map.count(element) takes less time than Map[element] | I was trying this problem on leetcode,
https://leetcode.com/problems/naming-a-company/description/ .
I've observed the following
My Code :
long long distinctNames(vector<string>& ideas) {
unordered_map<string,bool> isPresent;
vector<vector<long long>> dp(26,vector<long long>(26,0));
int n = ideas.size();
long long ans = 0;
for(int i = 0; i < n; i++)
isPresent[ideas[i]] = true;
for(int i = 0; i < n; i++)
{
char x = ideas[i][0];
string ts = ideas[i];
for(int j = 0; j < 26; j++)
{
char y = 'a' + j;
ts[0] = y;
if(!isPresent[ts])
dp[x-'a'][j]++;
}
}
for(int i = 0; i < 26; i++)
{
for(int j = 0; j < 26; j++)
{
if(i==j) continue;
ans += (dp[i][j] * dp[j][i]);
}
}
return ans;
}
This code was getting TLE (85/89).
But, in the same code, if I replace
!isPresent[ts]
with
!isPresent.count(ts)
Same code runs much faster and passes.
Anyone can explain why ?
| isPresent[ts] returns a reference to a map value object (so you can write isPresent[ts] = something. So if ts is not present in the map, then isPresent[ts] must default construct a map entry so that it has something to return a reference to. This is the reason that map::operator[] is not const.
isPresent.count(ts) has no such problems. If the ts key is not present then the map is unchanged.
|
72,590,220 | 72,590,294 | What happens during the process of cin.get()? | The code is as follows, when I enter "101010^Z000", my output becomes "000". Obviously, my input is invalid after it becomes "^Z". However, why can I continue typing after typing "^Z"? According to the code, shouldn't it have jumped out of the loop and ended the program at this time? I'm curious.
int main()
{
const int num = 20;
int a[num];
int i = 0;
while((a[i]=cin.get())!=EOF)
{
a[i] = cin.get();
cout.put(a[i]);
i++;
}
cout << a;
}
like this:
And, after this I keep typing "ssss" and the program still outputs "ss" as if the loop is continuing.
| Input is usually buffered. There is nothing in C++ that says it must be buffered but usually it is. What this means is that when your program is waiting for input it waits for a whole line of input. That whole line of input goes into a buffer and subsequent reads take characters from the buffer until it is empty. Then the next read will cause the program to wait again, and again it will wait for a whole line of input to be entered.
If you want unbuffered input then I've afraid there is no way to get that in standard C++. You have to use platform specific functions for that.
|
72,590,345 | 72,590,522 | Using std::ranges algorithms with custom containers and iterators | I have the following simplified code representing a range of integers that I want to use with various std algorithms. I am trying to update my code to use C++20's ranges versions of the algorithms so I can delete all of the begin() and end() calls. In the below code, std::any_of works with my container and iterator, but std::ranges::any_of does not.
#include <iostream>
#include <algorithm>
class Number_Iterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = int;
using difference_type = int;
using pointer = int*;
using reference = int&;
Number_Iterator(int start) noexcept : value(start) {}
Number_Iterator& operator++() noexcept { ++value; return *this; }
bool operator==(const Number_Iterator& other) const noexcept = default;
int operator*() const noexcept { return value; }
private:
int value;
};
class Numbers {
public:
Numbers(int begin, int end) noexcept : begin_value(begin), end_value(end) {}
Number_Iterator begin() const noexcept { return {begin_value}; }
Number_Iterator end() const noexcept { return {end_value}; }
private:
int begin_value;
int end_value;
};
int main() {
const auto set = Numbers(1, 10);
const auto multiple_of_three = [](const auto n) { return n % 3 == 0; };
// Compiles and runs correctly
if(std::any_of(set.begin(), set.end(), multiple_of_three)) {
std::cout << "Contains multiple of three.\n";
}
// Does not compile
if(std::ranges::any_of(set, multiple_of_three)) {
std::cout << "Contains multiple of three.\n";
}
return 0;
}
When I try to compile the above code, I get the following error messages from Visual Studio 2019 (16.11.15) with the flag /std:c++20:
Source.cpp(42,21): error C2672: 'operator __surrogate_func': no matching overloaded function found
Source.cpp(42,7): error C7602: 'std::ranges::_Any_of_fn::operator ()': the associated constraints are not satisfied
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\algorithm(1191): message : see declaration of 'std::ranges::_Any_of_fn::operator ()'
I have tried looking at the std::ranges::_Any_of_fn::operator() declaration, but I find myself more confused by that.
What am I missing to get the std::ranges algorithms to work with my container?
For the curious, what I'm actually iterating over are squares on a chess board, but those are represented by integers, so the difference from the above code isn't so great.
| To use your range with any_of it must satisfy the input_range concept:
template< class T >
concept input_range =
ranges::range<T> && std::input_iterator<ranges::iterator_t<T>>;
Then via the input_iterator concept:
template<class I>
concept input_iterator =
std::input_or_output_iterator<I> &&
std::indirectly_readable<I> &&
requires { typename /*ITER_CONCEPT*/<I>; } &&
std::derived_from</*ITER_CONCEPT*/<I>, std::input_iterator_tag>;
and via the input_or_output_iterator concept
template <class I>
concept input_or_output_iterator =
requires(I i) {
{ *i } -> /*can-reference*/;
} &&
std::weakly_incrementable<I>;
you land in the weakly_incrementable concept:
template<class I>
concept weakly_incrementable =
std::movable<I> &&
requires(I i) {
typename std::iter_difference_t<I>;
requires /*is-signed-integer-like*/<std::iter_difference_t<I>>;
{ ++i } -> std::same_as<I&>; // pre-increment
i++; // post-increment
};
in which you see that the iterator must have both the pre-increment and post-increment versions of operator++.
The iterator must also be default constructible because std::ranges::end creates a sentinel:
template< class T >
requires /* ... */
constexpr std::sentinel_for<ranges::iterator_t<T>> auto end( T&& t );
And sentinel_for
template<class S, class I>
concept sentinel_for =
std::semiregular<S> &&
std::input_or_output_iterator<I> &&
__WeaklyEqualityComparableWith<S, I>;
requires it to satisfy semiregular:
template <class T>
concept semiregular = std::copyable<T> && std::default_initializable<T>;
But without being default constructible, this substitution will fail:
template < class T >
concept default_initializable = std::constructible_from<T> && requires { T{}; } && ...
|
72,590,567 | 72,644,193 | use mariadb-connector-cpp with cmake project | github repo. i am using c++20 with cmake on visual studio to program on wsl and getting error loading shared library. can't find file libmariadb.so.3.
I used the build instructions to build it for Debian & Ubuntu on wls and it was installed in these paths.
so in my cmake I included
find_package(mariadbcpp)
include_directories("/usr/local/include/mariadb")
link_directories("/usr/local/lib/mariadb")
target_link_libraries(${PROJECT_NAME} mariadbcpp)
when I run I get the following error
error while loading shared libraries: libmariadb.so.3: cannot open shared object file: No such file or directory
I tried running
sudo /sbin/ldconfig -v
and I also tried including this in my top level cmake
SET(CMAKE_SKIP_BUILD_RPATH FALSE)
SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
SET(CMAKE_INSTALL_RPATH "/usr/local/lib/mariadb")
| to get it working you just need to add this to your cmake
include_directories("/usr/include/mariadb") #path to include folder
add_library(mariadbcpp STATIC IMPORTED)
set_property(TARGET mariadbcpp PROPERTY IMPORTED_LOCATION "/usr/lib/libmariadbcpp.so") #path to libmariadbcpp.so
then just include
#include <conncpp.hpp>
in source
to install I followed this Debian/Ubuntu and in step 10 the command to install libmariadbcpp.so.3 and lib/mariadb... should have been lib64/mariadb...
like so
sudo install lib64/mariadb/libmariadbcpp.so /usr/lib
sudo install lib64/mariadb/libmariadbcpp.so.3 /usr/lib
sudo install lib64/mariadb/plugin/* /usr/lib/mariadb/plugin
|
72,591,064 | 72,591,154 | Strange behavior between `std::make_unique` and `std::unique_ptr` with forward declaration | std::make_unique<T> needs C++ 17 feature.It's a pity that I have to use C++11. When I am porting the code snippet to C++11, I found a strange thing.
The code snippet which uses make_unique works well:
#include <iostream>
#include <memory>
struct View;
struct Database : public std::enable_shared_from_this<Database>
{
static std::shared_ptr<Database> Create(){ return std::shared_ptr<Database>(new Database());}
std::unique_ptr<View> GetView() { return std::make_unique<View>(shared_from_this()); } //works well
~Database() {std::cout << "Database is destoryed" << std::endl;}
private:
Database(){};
};
struct View
{
std::shared_ptr<Database> db;
View(std::shared_ptr<Database> db) : db(std::move(db)) {}
~View() {std::cout << "View is destoryed" << std::endl;}
};
int main()
{
std::shared_ptr<View> view;
{
auto db{Database::Create()} ;
view = db->GetView();
}
}
whereas the code snippet below does not compile:
#include <iostream>
#include <memory>
struct View;
struct Database : public std::enable_shared_from_this<Database>
{
static std::shared_ptr<Database> Create(){ return std::shared_ptr<Database>(new Database());}
std::unique_ptr<View> GetView() { return std::unique_ptr<View>(new View(shared_from_this())); } //here is the modification
~Database() {std::cout << "Database is destoryed" << std::endl;}
private:
Database(){};
};
struct View
{
std::shared_ptr<Database> db;
View(std::shared_ptr<Database> db) : db(std::move(db)) {}
~View() {std::cout << "View is destoryed" << std::endl;}
};
int main()
{
std::shared_ptr<View> view;
{
auto db{Database::Create()} ;
view = db->GetView();
}
}
Here is what the complier complains:
<source>: In member function 'std::unique_ptr<View> Database::GetView()':
<source>:10:95: error: invalid use of incomplete type 'struct View'
10 | std::unique_ptr<View> GetView() { return std::unique_ptr<View>(new View(shared_from_this())); } //here is the modification
| ^
<source>:4:8: note: forward declaration of 'struct View'
4 | struct View;
| ^~~~
After I did some modification for the second code snippet,this one works:
#include <iostream>
#include <memory>
struct Database;
struct View
{
std::shared_ptr<Database> db;
View(std::shared_ptr<Database> db) : db(std::move(db)) {}
~View() {std::cout << "View is destoryed" << std::endl;}
};
struct Database : public std::enable_shared_from_this<Database>
{
static std::shared_ptr<Database> Create(){ return std::shared_ptr<Database>(new Database());}
#if 0
std::unique_ptr<View> GetView() { return std::make_unique<View>(shared_from_this()); } //works well
#else
std::unique_ptr<View> GetView() { return std::unique_ptr<View>(new View(shared_from_this())); }
#endif
~Database() {std::cout << "Database is destoryed" << std::endl;}
private:
Database(){};
};
int main()
{
std::shared_ptr<View> view;
{
auto db{Database::Create()} ;
view = db->GetView();
}
}
Why std::make_unique<View>(shared_from_this()) works even if there is only a forward delaration for View before Database's definition, whereas the compiler complains about std::unique_ptr<View>(new View(shared_from_this()) under the same condition?
|
Why std::make_unique<View>(shared_from_this()) works even if there is only a forward delaration for View before Database's definition, whereas the compiler complains about std::unique_ptr<View>(new View(shared_from_this()) under the same condition?
Consider this simplified example:
#include <memory>
struct foo;
std::unique_ptr<foo> make_foo_1() { return std::make_unique<foo>(); } // OK
std::unique_ptr<foo> make_foo_2() { return std::unique_ptr<foo>(new foo); } // ERROR
struct foo {};
In make_foo_1, std::unique_ptr<foo> is made a dependent type in make_unique<foo> which means that it'll postpone binding to unique_ptr<foo>.
But "Non-dependent names are looked up and bound at the point of template definition" (i.e., the definition of std::unique_ptr<foo>) which means that, in make_foo_2, the definition of foo must have already been seen by the compiler or else it'll complain about foo being an incomplete type.
|
72,591,378 | 72,591,457 | The game loop designing | There is the simple game loop proposal:
double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
double current = getCurrentTime();
double elapsed = current - previous;
previous = current;
lag += elapsed;
processInput();
while (lag >= MS_PER_UPDATE)
{
update();
lag -= MS_PER_UPDATE;
}
render();
}
I think that the solution do have one serous drawback. Let's assume that (in some rather very uncommon case) the lag is about as huge as 3 seconds. In such a case if the MS_PER_UPDATE == 16msec (1/(60 fps)) the update function in internal loop (while (lag >= MS_PER_UPDATE)) will run 180 times! Taking into consideration that the update function may take some not very large but still decent time needed to there will be a significant.
Wouldn't the following:
double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
double current = getCurrentTime();
double elapsed = current - previous;
previous = current;
lag += elapsed;
processInput();
if (lag >= MS_PER_UPDATE)
{
update(lag);
lag = 0;
}
render();
}
solution be better?
Here instead of calling the render function 180 time I call the render only ONCE but with lag as a parameter. And inside the render the game objects are updated (say moved) proportionally to the vale of the passed lag so if for. e.g. the lag was 5 times > then the default fps (1/60) we just move all objects 5x instead of 1x?
| The whole point of games loops with fixed-size step is to decouple rendering and physics to retain stability, determinism in face of variable FPS.
You cannot simply update physics with 5 times larger step and expect it to be equal to updating 5x with the original step. That is simply not possible. With high enough step, numerical calculations will break down - fast collisions will be missed, objects will clip into each other, some might "explode".
So yes, you can go back to variable-sized time step of course, but you will get back all the drawbacks due to which it was abandoned.
|
72,591,704 | 72,609,958 | QT Creator C++ : Passing information from QDialog to MainWindow | I'm trying to make a program with the following:
In MainWindow (QMainWindow), I have a button AddUser that's opens a secondary window (QDialog) where I have 3 spaces to write the name, email and mobile number of user to add to program.
I want that, after introduce all those information, I click in Add button and the window closes and the information I wrote goes to a vector of User (vector<User> users) located in MainWindow so I can use it.
I have all of this stuff done, just the passing information I can't do.
I already searched about it but I just found make a login window (secondary window opens before main window and after introduce data it closes the login window and open the main window with that information saved). I want basically that but the difference is that secondary window opens when I click in a button in MainWindow
But it's not working well, can someone help me?
I have this code (based on Login context code):
adduserwindow.h (secondary window)
signals:
void add(const User & user);
adduserwindow.cpp
void AddUserWindow::on_button_addUser_clicked() // Add button after write the info
{
QString name = ui->text_name->text();
QString email = ui->text_email->text();
QString mobile = ui->text_mobile->text();
User u1(name.toStdString(),email.toStdString(),mobile.toStdString());
users_.push_back(u1);
emit add(u1);
}
mainwindow.h
public:
void setUser(const User &user);
private:
User mUser;
mainwindow.cpp
void MainWindow::on_button_adduser_clicked() // AddUser button in MainWindow
{
AddUserWindow adduser_window(this);
adduser_window.exec();
QObject::connect(&adduser_window, &AddUserWindow::add, [this](const User user) {
this->setUser(user);
this->show();
});
}
void MainWindow::setUser(const User& user)
{
mUser = user;
qDebug()<<mUser.toString(); //toString() is a method of User class to convert std::string to QString
}
Obs: I have this at the end of User.h:
Q_DECLARE_METATYPE(User)
| Just to leave an answer for future visitors... The issue here was that QDialog's exec() function does not return until the user closes the dialog. In this case the simple solution is to make any signal connections before calling exec().
However, its documentation recommends using open(), or alternatively show() for modeless dialogs. These functions both return immediately, so the dialog's lifetime would need to be tied to its parent window, by giving it dynamic storage duration:
void MainWindow::on_button_adduser_clicked() // AddUser button in MainWindow
{
auto* adduser_window = new AddUserWindow(this);
QObject::connect(adduser_window, &AddUserWindow::add, [this](const User user) {
this->setUser(user);
this->show();
});
adduser_window.open();
}
That is the idiomatic Qt way of doing it and I would recommend it, because it works whether or not the dialog (or other QObject) will actually outlive the function.
|
72,591,993 | 72,592,166 | How do I link different nodes of an std::list? | If I have an std::list of size 6 (contains 6 elements). I want to take the front node, disconnect it from the second node so that the second node becomes the front/head), and attach the original front node to the back so that the front node is now the back() or tail. In plainer language, I want to remove the node from the front and attach it to the back. However remove() function is iterative function that searches the entire container, and erase() destroys the actual node itself, which will mean deallocation of memory. I just want to disconnect the node and reattach it to the back. Can this be done? Also can this be done to insert at a random point in the linked list (like in the middle)?
| Use std::list::splice:
#include <iostream>
#include <iterator>
#include <list>
int main()
{
std::list<int> x = {1,2,3,4,5,6};
x.splice(x.end(), x, x.begin());
for (int elem : x)
std::cout << ' ' << elem;
std::cout << '\n';
// Prints 2 3 4 5 6 1
}
|
72,592,195 | 72,593,625 | Trying to match on a c-style array in gmock is failing at compile time | Background:
I'm mocking a hardware i2c transmit function, and trying to match on an array passed into it. This is in an embedded context, hence the c-style arrays and lack of STL containers.
Trying to match my second parameter, a c-style array (the buffer below), is failing at compile time.
Setup:
The interface defined as:
virtual I2C_Status_e i2c1Transmit(uint8_t address,
const uint8_t buffer[],
uint8_t length) = 0;
And I'm setting up my test mock as:
MOCK_METHOD(I2C_Status_e,
i2c1Transmit,
(uint8_t address, const uint8_t buffer[], uint8_t length),
(override));
Call point in the binary (this transmit sends a single 8-bit command):
status = hal->i2c1Transmit(address, readStatusCommand, 1);
Where readStatusCommand is def as:
const uint8_t readStatusCommand[1] = {0x00};
Test Code:
Here readStatusCommand has an identical signature to the one above.
EXPECT_CALL(hal, i2c1Transmit(address0, ElementsAreArray(readStatusCommand, 1), txLength))
.WillOnce(Return(HAL_Ok));
Compiler Output:
/home/.../vendor/gtest/googletest-release-1.10.x/googlemock/include/gmock/gmock-matchers.h: In instantiation of ‘class testing::internal::ElementsAreMatcherImpl<const unsigned char* const&>’:
/home/.../vendor/gtest/googletest-release-1.10.x/googlemock/include/gmock/gmock-matchers.h:3518:31: required from ‘testing::internal::ElementsAreArrayMatcher<T>::operator testing::Matcher<T>() const [with Container = const unsigned char*; T = unsigned char]’
/home/.../..._tests.cpp:88:5: required from here
^^^* Note: Expect Call above is line 88 here. *^^^
/home/.../vendor/gtest/googletest-release-1.10.x/googlemock/include/gmock/gmock-matchers.h:3084:45: error: ‘testing::internal::ElementsAreMatcherImpl<const unsigned char* const&>::StlContainer’ {aka ‘const unsigned char*’} is not a class, struct, or union type
3084 | typedef typename StlContainer::value_type Element;
| ^~~~~~~
/home/.../vendor/gtest/googletest-release-1.10.x/googlemock/include/gmock/gmock-matchers.h:3218:43: error: ‘testing::internal::StlContainerView<const unsigned char*>::type’ {aka ‘const unsigned char*’} is not a class, struct, or union type
3218 | ::std::vector<Matcher<const Element&> > matchers_;
| ^~~~~~~~~
Expected behavior/What I tried:
According to the matcher documentation here, it should work? ElementsAreArray is defined as working on c-style arrays if a length is passed in. I tried ElementsAre to the same effect.
It's also definitely the matcher, switching the matcher for ::_ allows it to compile fine.
| No, it should not work - the matcher documentation refers to the case where the argument being matched is an STL container, whereas const uint8_t buffer[] is a pointer.
The ElementsAreArray(readStatusCommand, 1) is a matcher for a container of length 1. However the second argument that it is being compared with doesn't have an associated length.
This will work, see ii. in These matchers can also match notes, that refers to Multi-argument Matchers.
EXPECT_CALL(hal, i2c1Transmit(address0, _, _))
.With(Args<1, 2>(ElementsAreArray(readStatusCommand)))
.WillOnce(Return(HAL_Ok));
ElementsAreArray(readStatusCommand) does not require setting the explicit array length, since readStatusCommand has type const uint8_t[1] that has an associated length.
|
72,592,338 | 72,593,924 | Getting Segmentation Fault while Inserting Elements in 2d Vector in Microsoft Visual Studio 2019 | I am writing a program in which I sum all of the elements in a 2d vector and find out whether the sum of them is 0 or not.
Getting Error which I mentioned above in the title as well as in online editor I am getting error - Segmentation Fault
#include <iostream>
#include<vector>
using namespace std;
int main()
{
int num;
cin >> num;
vector<vector<int>> arr;
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
cin >> arr[i][j];
}
}
int ans = 0;
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
ans = ans + arr[i][j];
}
}
if (ans == 0)
cout << "YES";
else
cout << "NO";
return 0;
}
| #include <iostream>
#include<vector>
using namespace std;
int main()
{
//User Input
int num {};
cout << "Enter a Number: ";
cin >> num;
//Init Vector
vector <int> V1;
vector <int> V2;
vector<vector<int>> V2D;
//Instead of std:cin we use push back;
for (int i {}; i < num; i++){
V1.push_back(i);
}
for (int j {}; j < num; j++){
V2.push_back(j);
}
//Now we combine the Vectors to a 2D Vector
V2D.push_back(V1);
V2D.push_back(V2);
//Display Vector
//The First Vector is .at(0) and cycles through with each iteration
for(int i {};i<V2D.at(0).size();i++){
cout << V2D.at(0).at(i) << " ";
}
cout << endl;
//The Second Vector is .at(1) and gets Cycled through
for(int j {};j<V2D.at(1).size();j++){
cout << V2D.at(1).at(j) << " ";
}
//The more Vectors you add, the higher the first .at Position gets
//You can mess around with my code and try to implement your idea if you like
//if (ans == 0)
//cout << "YES";
//else
//cout << "NO";
return 0;
}
You dont have to use a total of 3 Vectors, but I find it easier to explain it like that.
|
72,592,481 | 72,592,764 | How to do typecast with prestored typeid(T) during runtime? | I created a resource system in CPP:
template<typename T>
class Resource{
public:
Resource() {}
void push(std::shared_ptr<T> pRes) {
_items.emplace(_nextId++, pRes);
}
friend class ResourceManager;
private:
size_t _nextId{ 0 };
std::unordered_map<size_t, std::shared_ptr<T>> _items;
};
class ResourceManager{
public:
ResourceManager() {}
~ResourceManager() {
for (auto& pair : _resources) delete pair.second;
}
template<typename T>
void register() {
Resource<T>* pRes = new Resource<T>;
_resources.emplace(typeid(T).name(), (void*)pRes);
}
template<typename T>
Resource<T>& getResource(){
return *(T*)_resources[typeid(T).name()];
}
private:
std::unordered_map<std::string, void*> _resources;
};
Now I want to add a method to ResourceManager to modify all registered resources inside _resources. How can I typecast void* with stored typeid(T).name()?
| You can't because the type needs to be known at compile time, and the keys of the map are not.
There are a few issues with your implementation: you're deleting a void* in your destructor (which is UB), and your getResource function returns a T instead of a Resource<T>.
A solution is to have some type erasure (via virtual functions):
class ErasedResource {
private:
ErasedResource() = default;
ErasedResource(ErasedResource&&) = default;
template<typename T>
friend class Resource;
friend class ResourceManager;
void push(std::shared_ptr<void> pRes) {
_items.emplace(_nextId++, std::move(pRes));
}
size_t _nextId{ 0 };
// Store an "untyped" shared_ptr
std::unordered_map<size_t, std::shared_ptr<void>> _items;
public:
virtual ~ErasedResource() = default;
};
template<typename T>
class Resource : public ErasedResource {
public:
Resource() = default;
Resource(ErasedResource&&) = delete;
Resource(Resource&&) = default;
void push(std::shared_ptr<T> pRes) {
ErasedResource::push(std::static_pointer_cast<void>(std::move(pRes)));
}
friend class ResourceManager;
private:
std::shared_ptr<T> get(std::size_t index) const {
auto it = _items.find(index);
if (it == _items.end()) return nullptr;
return std::static_pointer_cast<T>(it->second);
}
};
class ResourceManager{
public:
ResourceManager() = default;
template<typename T>
void register() {
std::unique_ptr<ErasedResource> pRes(new Resource<T>);
_resources.emplace(std::type_index(typeid(T)), std::move(pRes));
}
template<typename T>
Resource<T>& getResource() const {
ErasedResource& res = *_resources.at(std::type_index(typeid(T)));
return static_cast<Resource<T>&>(res);
}
private:
// Switch to `type_index` (for performance)
// and `unique_ptr` (to avoid writing a destructor)
std::unordered_map<std::type_index, std::unique_ptr<ErasedResource>> _resources;
};
And if you want some function to operate on each resource that uses the type T, add a virtual function to do it. For example, if you wanted to call "item.f()" for each item in the resource, add a virtual void call_f() = 0 function to ErasedResource and override it in Resource<T>.
|
72,592,535 | 72,599,961 | Can I get the namespaces/function/classes hierarchy of an object instance? - c++ | I have an external Parameter class I need to define as global objects (instances) inside different namespaces. I insert a pointer to each instance of the class to a map.
the problem:
not all parameter names are unique and I need a unique name as key to each instance, can I get the namespace hierarchy of the object name as prefix for his name?
RegisteredGlobalObject.cpp:
RegisteredGlobalObject::RegisteredGlobalObject(const string& uid, int val) {
m_mapUidToParamPair[uid] = val;
}
ParamsDef.h:
namespace base {
namespace vpeservice {
extern RegisteredGlobalObject int_64_param;
} // namespace vpeservice
namespace otherservice {
extern RegisteredGlobalObject int_64_param;
} // namespace otherservice
} // namespace base
ParamsDef.cpp:
namespace base {
namespace vpeservice {
RegisteredGlobalObject int_64_param(getInstatnceDefenitionPlaceStr()+"int_64_param", 1);
}
namespace otherservice {
RegisteredGlobalObject int_64_param(getInstatnceDefenitionPlaceStr()+"int_64_param", 2);
}
}
can I implement the function getInstatnceDefenitionPlaceStr() which returns "base::vpeservice" for the first call and "base::otherservice" for the second?
| OK, this is my solution to this case.
hope it will help someone.
I defined a macro for every internal namespace that will define a function inside the namespace to get current __PRETTY_FUNCTION__ path.
then I used How to get a fully-qualified function name in C++ (gcc) with some modifications (you can see the f(__PRETTY_FUNCTION__,__func__) call inside the macro:
#define PARAMETERS_SECTION(name) namespace name {\
std::string getPath()\
{\
return f(__PRETTY_FUNCTION__,__func__);\
}\
#define configureParam(type, name, val) RegisteredGlobalObject name(getPath()+#name, val);
then I changed ParamsDef.cpp to be:
namespace base {
PARAMETERS_SECTION(vpeservice) {
configureParam(int64_t, int_64_param, 1)
}
PARAMETERS_SECTION(otherservice) {
configureParam(int64_t, int_64_param, 2)
}
}
and got keyes:
base::vpeservice::int_64_param
base::otherservice::int_64_param
|
72,592,536 | 72,592,814 | Thread-safety of reference count in std::shared_ptr | Looking at this implementation of std::shared_ptr https://thecandcppclub.com/deepeshmenon/chapter-10-shared-pointers-and-atomics-in-c-an-introduction/781/ :
Question 1 : I can see that we're using std::atomic<int*> to store the pointer to the reference count associated with the resource being managed. Now, in the destructor of the shared_ptr, we're changing the value of the ref-count itself (like --(*reference_count)). Similarly, when we make a copy of the shared_ptr, we increment the ref-count value. However, in both these operations, we're not changing the value of the pointer to the ref-count but rather ref-count itself. Since the pointer to ref-count is the "atomic thing" here, I was wondering how would ++ / -- operations to the ref-count be thread-safe? Is std::atomic implemented internally in a way such that in case of pointers, it ensures changes to the underlying object itself are also thread-safe?
Question 2 : Do we really need this nullptr check in default_deleter class before calling delete on ptr? As per Is it safe to delete a NULL pointer?, it is harmless to call delete on nullptr.
| Question 1:
The implementation linked to is not thread-safe at all. You are correct that the shared reference counter should be atomic, not pointers to it. std::atomic<int*> here makes no sense.
Note that just changing std::atomic<int*> to std::atomic<int>* won't be enough to fix this either. For example the destructor is decrementing the reference count and checking it against 0 non-atomically. So another thread could get in between these two operations and then they will both think that they should delete the object causing undefined behavior.
As mentioned by @fabian in the comments, it is also far from a correct non-thread-safe shared pointer implementation. For example with the test case
{
Shared_ptr<int> a(new int);
Shared_ptr<int> b(new int);
b = a;
}
it will leak the second allocation. So it doesn't even do the basics correctly.
Even more, in the simple test case
{
Shared_ptr<int> a(new int);
}
it leaks the allocated memory for the reference counter (which it always leaks).
Question 2:
There is no reason to have a null pointer check there except to avoid printing the message. In fact, if we want to adhere to the standard's specification of std::default_delete for default_deleter, then at best it is wrong to check for nullptr, since that is specified to call delete unconditionally.
But the only possible edge case where this could matter is if a custom operator delete would be called that causes some side effect for a null pointer argument. However, it is anyway unspecified whether delete will call operator delete if passed a null pointer, so that's not practically relevant either.
|
72,593,516 | 72,593,601 | Reading space-separated numbers from cin in C++ | I have to put the numbers from each line of input into different vectors without knowing how many numbers there will be in one line of input. For example:
1 2 3
4 5 6 -7
should result in
a = {1, 2, 3};
b = {4, 5, 6, -7};
Note that the number of integers in each line is unknown.
I've tried using stringstream but for some reason it didn't work for two lines of input:
int main() {
vector<int> a, b;
string c;
int number;
stringstream lineOfInput;
getline(cin, c);
lineOfInput.str(c);
c = "";
while (lineOfInput >> number) {
a.push_back(number);
}
getline(cin, c);
lineOfInput.str(c);
c = "";
while (lineOfInput >> number) {
b.push_back(number);
}
return 0;
}
The first vector is filled normally, but the second doesn't. Is there a good way to extract numbers from lines (without using boost library) and what's the problem with my code?
| When you use lineOfInput as a condition in a while loop it will run until it enters the fail state, so the second while with the same stringstream will never run because it doesn't return true. Just add lineOfInput.clear() and everything will be all right.
Also when you run into a problem like this it's helpful to debug and see what really happens.
|
72,593,803 | 72,593,946 | Prime number check doesn't work as it should | I'll try to keep this short. So my task is to find the last prime number in an array, if there's any. But right now my program assigns any number it wants from the array to the lastPrimeNumber variable. Any ideas?
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
int numbers[10] = {0};
int numbersCount = 10;
bool areEven = true;
cout << "Numbers: ";
for (int i = 0; i < numbersCount; i++)
{
numbers[i] = rand() % 10 + 1;
cout << numbers[i] << " ";
}
for (int i = 0; i < numbersCount; i++)
{
if (numbers[i] % 2 != 0)
{
cout << "\nNot all numbers are even" << endl;
areEven = false;
break;
}
if (areEven)
{
cout << "\nAll numbers are even" << endl;
break;
}
}
// Looking for the last prime number in an array
int lastPrimeNumber = 0;
bool isPrime = true;
for (int i = 0; i < numbersCount; i++)
{
for (int j = 2; j < numbers[i]/2; j++)
{
if (numbers[i] % j == 0 || numbers[i] < 2)
{
isPrime = false;
}
}
if(isPrime)
{
lastPrimeNumber = numbers[i];
}
}
cout << endl << lastPrimeNumber;
return 0;
}
Thanks in advance.
| For starters this for loop
for (int i = 0; i < numbersCount; i++)
{
if (numbers[i] % 2 != 0)
{
cout << "\nNot all numbers are even" << endl;
areEven = false;
break;
}
if (areEven)
{
cout << "\nAll numbers are even" << endl;
break;
}
}
contains a logical error. If the first element of the array is an even value then the program outputs
cout << "\nAll numbers are even" << endl;
that in general is wrong.
Instead you should write for example
for (int i = 0; areEven && i < numbersCount; i++)
{
areEven = numbers[i] % 2 == 0;
}
if ( areEven )
{
cout << "\nAll numbers are even" << endl;
}
else
{
cout << "\nNot all numbers are even" << endl;
}
Within these for loops
int lastPrimeNumber = 0;
bool isPrime = true;
for (int i = 0; i < numbersCount; i++)
{
for (int j = 2; j < numbers[i]/2; j++)
{
if (numbers[i] % j == 0 || numbers[i] < 2)
{
isPrime = false;
}
}
if(isPrime)
{
lastPrimeNumber = numbers[i];
}
}
you do not reset the variable isPrime before the inner for loop.
And the condition in the for loop is incorrect
for (int j = 2; j < numbers[i]/2; j++)
Due to the condition the number 4 can be considered as a prime number.
And moreover this condition
numbers[i] < 2
in this if statement
if (numbers[i] % j == 0 || numbers[i] < 2)
can never evaluate to true.
At least you should write
int lastPrimeNumber = 0;
for (int i = 0; i < numbersCount; i++)
{
bool isPrime = not ( numbers[i] < 2 );
for (int j = 2; isPrime && j <= numbers[i]/2; j++)
{
if (numbers[i] % j == 0)
{
isPrime = false;
}
}
if(isPrime)
{
lastPrimeNumber = numbers[i];
}
}
A better approach is the following.
int lastPrimeNumber = 0;
for (int i = 0; i < numbersCount; i++)
{
bool isPrime = numbers[i] % 2 == 0 ? numbers[i] == 2 : numbers[i] != 1;
for ( int j = 3; isPrime && j <= numbers[i] / j; j += 2 )
{
if (numbers[i] % j == 0)
{
isPrime = false;
}
}
if(isPrime)
{
lastPrimeNumber = numbers[i];
}
}
|
72,594,333 | 74,320,491 | Arduino RP2040 Pico Unique ID | I am using Raspberry pi pico on Arduino IDE. I am using this library githublink for it. There is 3 examples in this link, ArduinoUniqueID and ArduinoUniqueID8
doesn't print anything. Ide says
WARNING: library ArduinoUniqueID claims to run on avr, esp8266, esp32, sam, samd, stm32 architecture(s) and may be incompatible with your current board which runs on mbed_rp2040 architecture(s).
(but GitHub says we add RP2040)
When I try to use last example ArduinoUniqueIDSerialUSB , It prints something but they are not correct values. It prints these :
UniqueID: 30 00 33 00 39 00 31 00 36 00 30 00 45 00 36 00 32 00 41 00 38 00 32 00 34 00 38 00 43 00 33 00
UniqueID: 34 00 38 00 43 00 33 00
The correct unique ID values here : (I printed these with micropython)
hex value of s = e660a4931754432c
type s = <class 'bytes'>
s = b'\xe6`\xa4\x93\x17TC,'
I don't even know what type 34 00 38 00 43 00 33 00 are, I try to convert hex but it prints same thing.
How can I find pico's Unique ID with Arduino Code ?
| A unique ID for the Pico (and most RP2040 boards) is determined by the serial number of the flash. The Pico SDK has functions to get that ID. Either you can retrieve it directly from the flash by using flash_get_unique_id(uint8_t* id_out) which is what the library linked above did. The documentation for that is here.
Alternatively, you can get the unique ID from the MCU. The two functions for retrieving the ID are pico_get_unique_board_id(pico_unique_board_id_t* id_out) which returns the ID as a hex array or pico_get_unique_board_id_string(char* id_out, uint len) which returns it as a string. The documentation for that is here.
Those values are hex and are coming from their Unique_ID buffer which it looks like is being improperly filled with the Unique id. The code below should instead do what you need.
uint8_t UniqueID[8];
void UniqueIDdump(stream)
{
flash_get_unique_id(UniqueID);
stream.print("UniqueID: ");
for (size_t i = 0; i < 8; i++)
{
if (UniqueID[i] < 0x10)
stream.print("0");
stream.print(UniqueID[i], HEX);
stream.print(" "); }
stream.println();
}
|
72,594,484 | 72,594,727 | How to calculate prefix sum of tuple of std::integral_constant | I would like to calculate the prefix sum of std::integral_constants.
Given is a collection of std::integral_constant in a std::tuple.
Example
using in_t = std::tuple<
std::integral_constant<unsigned __int64,1>,
std::integral_constant<unsigned __int64,1>,
std::integral_constant<unsigned __int64,2>
>;
How can the the prefix sum be calculated at compile time, preferably in a way using a function that's return type is deduced (since template metaprogramming is pretty painful)?
template <typename Tuple>
constexpr decltype(auto) prefixSum(Tuple t) {
// ?
}
int main () {
using in_t = std::tuple<
std::integral_constant<unsigned __int64,1>,
std::integral_constant<unsigned __int64,1>,
std::integral_constant<unsigned __int64,2>
>;
using out_t = decltype(prefixSum<in_t>());
}
The return type should look like
std::tuple<
std::integral_constant<unsigned __int64,1>,
std::integral_constant<unsigned __int64,2>,
std::integral_constant<unsigned __int64,4>
>
I experienced various failure attempts, like a recursive way, passing the i'th partial sum to the next level as template argument. Not sure if that's a good approach at all, thinking of maximum recursion depth.
A failing example is
template <std::size_t I=0, std::size_t Offset=0, typename Tuple>
constexpr auto prefixSumRecursive(Tuple t) {
constexpr auto value = Offset + std::get<I>(t);
constexpr auto tuple = std::make_tuple(std::integral_constant<std::size_t, value>{});
if constexpr((I+1) < std::tuple_size_v<Tuple>) {
return std::tuple_cat(tuple, prefixSumRecursive<I + 1, value>(t));
}
return tuple;
}
| There is already an algorithm for prefix sum in the standard, i.e., std::inclusive_scan
#include <numeric>
#include <array>
#include <tuple>
using in_t = std::tuple<
std::integral_constant<int,1>,
std::integral_constant<int,1>,
std::integral_constant<int,2>
>;
template<int... values>
constexpr auto prefixSum(
std::tuple<std::integral_constant<int, values>...>) {
constexpr auto out = [] {
constexpr std::array in{values...};
std::remove_const_t<decltype(in)> out{};
std::inclusive_scan(in.begin(), in.end(), out.begin());
return out;
}();
return [=]<auto... Is>(std::index_sequence<Is...>) {
return std::tuple<std::integral_constant<int, out[Is]>...>{};
}(std::make_index_sequence<out.size()>());
}
using in_t = std::tuple<
std::integral_constant<int,1>,
std::integral_constant<int,1>,
std::integral_constant<int,2>
>;
using out_t = decltype(prefixSum(in_t{}));
Demo
|
72,594,660 | 72,594,749 | How to put multiple inputs in one variable C++ | I'm rather new to C++ and don't really know much about it. I want a solution where the user could type in something like this (on separate lines):
AAA
BBB
CCC
And store it in a variable like this:
AAABBBCCC
Each of the lines in the input are a separate cin. There is only one variable that will store all of this. Is it possible?
| Did you mean that 1 variable will store the result, or use just 1 variable throughout the whole program? If you meant the first one, given your inputs res will have AAABBBCCC at the end of the run:
std::string tmp;
std::string res;
for (int i = 0; i < 3; i ++) {
std::cin >> tmp;
res += tmp;
}
std::cout << res << std::endl;
You can just write res += tmp because std::string overloads the operator +=.
|
72,594,662 | 72,595,036 | condition in for loop with if operator | basically I have this function repeat I understand what it does, what I don't understand is the this part of the condition in the for loop v ? sizeof(g) / 8 : 0, if someone could explain it me I would appreciate a lot because I don't get what it does.
program:
char g[1024];
double *repeat(double *v) {
for (int i = 0; i < (v ? sizeof(g) / 8 : 0); i++)
{
if (v[i] > 2 * i)
v[i] = i;
else
v[i] = 0;
}
return v;
}
int main()
{
double *t;
*t = 2.0;
t = repeat(t);
printf("Numero: %f\n",*t);
return 0;
}
| This is somewhat obscure code, as illustrated by the number of incorrect attempts at answers. The key here is that the ?: operator makes an expression, that is, it's code that produces a value. So, first look at the value of the expression:
(v ? sizeof(g) / 8 : 0)
where v is a pointer. When a pointer is used in a context that expects a boolean value, the value is true if the pointer is not a null pointer, and false if it is. So, you could think of this expression as
(v != nullptr ? sizeof(g) / 8 : 0)
This expression is the upper bound of the for loop. The loop will execute for as long as i < (v ? sizeof(g) / 8 : 0) is true. So, if v is a null pointer, the condition is i < 0, which is false, and the body of the loop will not be run. If v is not a null pointer, the condition is i < sizeof(g)/8, and the body of the loop will be run as many times as whatever that value is.
|
72,594,913 | 72,595,445 | What is the best type of pointers to use in this situation | I'm currently making a small "Game Engine". I was wondering if I should use smart pointers and which type I should use. or do I just use raw pointers for this GameObject class. every instance of GameObject have Component attached to it Transform, sprite etc. should I use smart pointers or just raw pointers. because I have never used smart pointers and I always get a bunch of errors when I try to. will it be fine to use raw pointers?
GameObject.h:
class Component;
class GameObject{
public:
GameObject();
virtual ~GameObject();
void addComponent(Component* component);
//return the first component of type T
template<typename T>
T* getComponent(){
for(auto component : components){
if(dynamic_cast<T*>(component)){
return dynamic_cast<T*>(component);
}
}
}
// return the component with the type T
template<typename T>
std::vector<T*> getComponents(){
std::vector<T*> components;
for(auto component : this->components){
if(dynamic_cast<T*>(component)){
components.push_back(dynamic_cast<T*>(component));
}
}
return components;
}
void removeComponent(Component* component);
std::vector<Component*> components;
};
//======================================================
class Component
{
private:
public:
Component();
virtual ~Component();
//the game object this component is attached to
GameObject* gameObject;
};
Thanks for reading.
| First things first. In general early failure is preferred over late failure. Failure after delivery is catastrophy. The most welcome form of failure is at compile-time. Good code tried to prevent runtime or logic errors by asserting errors at compile-time. So don't be frightened by compile errors.
Next, you have to make a decision on lifespan of your objects and their ownership. The main problem with raw pointers is the ambiguity of implication; does a raw pointer imply:
Just a reference
An optional reference
An owned resource
An array beginning
PIMPL
...
It's hard to tell by looking at the code using raw pointers, which asspect was intended. Confusions during coding lead to all sort of evil(including resource leak, double delete, use-after-free ...).
Smart pointers on the other hand, limited the use case of pointed-to-object to a very specific case(from above list or else). Moreover, smart pointers provide guarantees about lifespan of the object. Standard library provides a variety of classes (smart pointer or else) for different use-cases above.
If none of those classes are appropriate for a specific use case, I would rather define a wrapper to encapsulate the pointer and decorate its behavior.
|
72,594,916 | 72,595,018 | Reverse linked list in a function, that also has to work with a linked list | I had to create a function, that deletes nodes that have a greater element to the right. I achieved this by creating 2 functions:
1st function reverses a list
2nd function that deletes nodes, that have a lesser value than the current node.
In order for this to work I reverse a list, call the 2nd function and reverse the list back.
My problem is: How can I combine these 2 functions together, so I can, for example call the reverse function inside the lesVal function without needing to call it separately.
void reverse(Elem** listHead){
Elem* next;
Elem* curr = *listHead;
Elem* temp = NULL;
while (curr != NULL){
next = curr->next;
curr->next = temp;
temp = curr;
curr = next;
}
*listHead = temp;
}
void lesVal(Elem* listHead){
Elem* temp;
Elem* curr = listHead;
Elem* compare = listHead;
while (curr != NULL && curr->next != NULL){
if (curr->next->number < compare->number){
temp = curr->next;
curr->next = temp->next;
delete temp;
}
else{
curr = curr->next;
compare = curr;
}
}
}
reverse(&first);
lesVal(first);
reverse(&first);
|
I had to create a function, that deletes nodes that have a greater
element to the right. I achieved this by creating 2 functions: 1st
function reverses a list 2nd function that deletes nodes, that have a
lesser value than the current node.
It is an inefficient approach. Your task is to delete nodes that have a greater element to the right. So you need to write one function that performs the deletion and nothing more,
The function is very simple.
void lesVal( Elem **listHead )
{
while ( *listHead && ( *listHead )->next )
{
if ( ( *listHead )->number < ( *listHead )->next->number )
{
Elem *tmp = *listHead;
*listHead = ( *listHead )->next;
delete tmp;
}
else
{
listHead = &( *listHead )->next;
}
}
}
If to include header <utility> then the function can have even less lines. For example
#include <utility>
//...
void lesVal( Elem **listHead )
{
while ( *listHead && ( *listHead )->next )
{
if ( ( *listHead )->number < ( *listHead )->next->number )
{
delete std::exchange( *listHead, ( *listHead )->next );
}
else
{
listHead = &( *listHead )->next;
}
}
}
Though as it is a C++ code then it is better to pass the pointer to the head node by reference. In this case the function will look like
void lesVal( Elem * &listHead )
{
for ( Elem **current = &listHead; *current && ( *current )->next; )
{
if ( ( *current )->number < ( *current )->next->number )
{
delete std::exchange( *current, ( *current )->next );
}
else
{
current = &( *current )->next;
}
}
}
If you want to repeat deletions of nodes until the list will be sorted in the descending order then a straightforward approach can look the following way.
void lesVal( Elem * &listHead )
{
bool removed = true;
while ( removed )
{
removed = false;
for ( Elem **current = &listHead; *current && ( *current )->next; )
{
if ( ( *current )->number < ( *current )->next->number )
{
removed = true;
delete std::exchange( *current, ( *current )->next );
}
else
{
current = &( *current )->next;
}
}
}
}
|
72,595,127 | 72,596,537 | Where do I put the -lncurses to properly link the ncurses library | I can't find a way to properly link the ncurses library. The same code compiled just right on mac, but won't compile on linux. I am getting an error saying undefined reference to waddnwstr. In the example I only use the mvwaddwstr function that expands to waddwstr and then to waddnwstr.
This is the error message I am getting:
/usr/bin/ld: Game.o: in function `Game::printIconInColor(int, int, wchar_t const*, int)':
/home/build/./src/include/Game.cpp:1058: undefined reference to `waddnwstr'
This is the piece of code that generates the error:
void Game::printIconInColor( int y, int x, const wchar_t* icon, int color ){
if( color ) wattron( m_window, COLOR_PAIR( color ) );
mvwaddwstr( m_window, y, x, icon );
if( color ) wattroff( m_window, COLOR_PAIR( color ) );
}
I have read a lot of similar questions on stack overflow, but none of them work, or I am getting it wrong...
Here is the makefile:
CXX = g++
CXXFLAGS = -g -Wall -pedantic -Iinclude -std=c++17 -O2 -D_XOPEN_SOURCE_EXTENDED
EXECUTABLE = game
OBJECTS = main.o Character.o MC.o NPC.o Potion.o Game.o
INC = ./src/include/
SRC = $(shell find $(INC) -type f -name '*.cpp')
LDFLAGS = -lncurses -lstdc++fs
all: compile run
compile: $(OBJECTS)
$(CXX) $(CXXFLAGS) -o $(EXECUTABLE) $(OBJECTS) $(LDFLAGS)
doc: $(SRC)
doxygen
run:
./$(EXECUTABLE)
clean:
rm $(EXECUTABLE) $(OBJECTS)
main.o: ./src/main.cpp
$(CXX) $(CXXFLAGS) -c ./src/main.cpp
Character.o: $(INC)Character.cpp
$(CXX) $(CXXFLAGS) -c $(INC)Character.cpp
NPC.o: $(INC)NPC.cpp
$(CXX) $(CXXFLAGS) -c $(INC)NPC.cpp
MC.o: $(INC)MC.cpp
$(CXX) $(CXXFLAGS) -c $(INC)MC.cpp
Potion.o: $(INC)Potion.cpp
$(CXX) $(CXXFLAGS) -c $(INC)Potion.cpp
Game.o: $(INC)Game.cpp
$(CXX) $(CXXFLAGS) -c $(INC)Game.cpp
Example that works on mac:
#include <ncurses.h>
int main(){
setlocale(LC_ALL, "");
initscr();
WINDOW * win = newwin( 10, 10, 10, 10 );
box( win, 0, 0 );
mvwaddwstr( win, 1, 1, L"\u238B" );
wgetch( win );
endwin();
return 0;
}
| Apple's bundled copy of ncurses (5.7) is configured for wide-character ncurses. For that platform (and perhaps a few others), the makefile could just use -lncurses.
But waddwnstr uses wchar_t parameters, which makes it a wide-character function. For the usual case, that is in the wide-character library, so you would use -lncursesw.
If you were using an add-on library (i.e., MacPorts or brew), that uses a symbolic link to allow either name to be used, to simplify porting.
Keeping things like this straight is generally done with configure scripts (to produce a correct makefile), so that your makefile would contain
LDFLAGS = -lncurses -lstdc++fs
or
LDFLAGS = -lncursesw -lstdc++fs
If both libraries were specified, the linker should complain about the duplicated symbols between the two libraries -- for most platforms other than MacOS.
When both libraries are available, the header files also are available, requiring some compiler (-I) options and/or source-modification to use the correct header (not just ncurses.h). Again, a configure script is the usual approach.
|
72,595,228 | 72,595,457 | How to find the count number of entries in map iterator in C++ | I am new in C++.I am using STL Containers.I am mapping the AnimalWeightCAT to unique values of distance travel in km.Using this code
#include <iostream>
#include <map>
#include <sstream>
int main() {
std::istringstream file(
"3 138 3 239 3 440 3 241 3 462 3 432 3 404 2 435 2 514 2 565 3 328 3 "
"138 5 401 5 142 5 404 5 460 5 472 2 418 5 510 2");
// some typedefs to make it simpler:
typedef int AnimalWeightCAT_t;
typedef int distance_t;
typedef int count_t;
typedef std::map<distance_t, count_t> distcount_t;
typedef std::map<AnimalWeightCAT_t, distcount_t> AWeightDistance;
AWeightDistance AWeightDistanceCount; // map AnimalWeightCAT -> distances with counts
AnimalWeightCAT_t AnimalWeightCAT; // temporary variable to read a AnimalWeightCAT
distance_t dist; // temporary variable to read a distance
// read AnimalWeightCAT and distance until the file is depleated and use AnimalWeightCAT and dist as
// keys in the outer and inner map and increase the count:
while (file >> AnimalWeightCAT >> dist) ++AWeightDistanceCount[AnimalWeightCAT][dist];
for(AWeightDistance::iterator adit= AWeightDistanceCount.begin(); adit!= AWeightDistanceCount.end(); ++adit) {
std::cout << "AnimalWeightCAT: " << adit->first << '\n';
for(distcount_t::iterator dcit = adit->second.begin();dcit != adit->second.end();++dcit){
std::cout << '\t' << dcit->first << ' ' << dcit->second << '\n';
}
}
}
How i can find the count of number of distict in indices of AnimalWeightCAT of iterator aditby using map in C++?
Above code display the following output
Output:
AnimalWeightCAT: 2
418 1
435 1
514 1
565 1
AnimalWeightCAT: 3
138 2
239 1
241 1
328 1
404 1
432 1
440 1
462 1
AnimalWeightCAT: 5
142 1
401 1
404 1
460 1
472 1
510 1
I want this kind of output.How?
AnimalWeightCAT: 2 count = 4
AnimalWeightCAT: 3 count = 8
AnimalWeightCAT: 5 count = 6
| For count of the second map adit->second.size() will be sufficient so your last loop, in order to look like you desire must be:
for(AWeightDistance::iterator adit = AWeightDistanceCount.begin();
adit != AWeightDistanceCount.end(); ++adit)
{
std::cout << "AnimalWeightCAT: " << adit->first
<< " count: " << adit->second.size() << '\n';
}
or simpler, using a range based for-loop:
for(auto&&[awc, dist_count] : AWeightDistanceCount) {
std::cout << "AnimalWeightCAT: " << awc
<< " count: "<< dist_count.size() << '\n';
}
|
72,595,324 | 72,595,374 | I'm having troubles trying to compile this C++ program with g++? | I'm using a macOS operating system & within the terminal I have installed g++, when trying to compile my C++ Program File, which has separate compilation; the following error message occurs:
main.cpp:3:10: fatal error: 'Item.h' file not found
#include "Item.h"
^~~~~~~~
1 error generated.
with the following command: g++ main.cpp -std=c++11
I'm assuming I have to compile the other programs. One is a header program which has a declared class, and in another .cpp program, it defines the class in the header program. Sorry if this explanation is poorly written or not that understanding, I'm having big troubles continuing my programming journey so if there's something you can't understand in this post please leave a comment on this post & I will do my best to explain the subject to you, thanks.
| If Item.h is not in your current directory, you will need to specify the directory containing it as an include directory in the g++ command. For example, if your folder structure is this:
.
├── headers
│ └── Item.h
├── items.cpp
└── main.cpp
Then your g++ command(s) should be
g++ -o main.o -std=c++11 -Iheaders -c main.cpp
g++ -o items.o -std=c++11 -Iheaders -c items.cpp
g++ -o program items.o main.o
Note that with separate translation units (cpp files), you need to compile each one to an object file first (.o file, that's what the -c option does), and then link them together with the last command.
Alternatively, with a small number of translation units, you can get away with compiling and linking them in one step:
g++ -o program -Iheaders -std=c++11 main.cpp items.cpp
I would definitely recommend setting up a Makefile or some other form of build system if you will have many translation units.
|
72,595,495 | 72,597,790 | fatal error: Eigen/Dense: No such file or directory: Eigen/Dense VS code and Ubuntu | I know this question been answered like a million time, and I have followed with each suggestion to no avail. I am trying to set up Eigen in my c++ code using VS code while running commands on Ubuntu 20.04 on windows. I was following with this specific post:
Post
This is my c_cpp_properties.cpp file:
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**",
"C:/cygwin64/usr/include/**",
"C:/Program Files/LLVM/bin/**",
"C:/Users/J/Documents/eigen-3.4.0/eigen-3.4.0",
"C:/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/**",
"C:/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/src/**",
"C:/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/test",
"C:/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/test/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.18362.0",
"compilerPath": "\"C:/Program Files/LLVM/bin/clang++.exe\"",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}
And following the suggestion from other posts, this is my tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe build active file",
"command": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"-I",
"C:\\Users\\J\\Documents\\eigen-3.4.0\\eigen-3.4.0\\Eigen\\",
],
"options": {
"cwd": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: \"C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe\""
}
]
}
Still getting the error:
Test.cpp:21:9: fatal error: Eigen/Dense: No such file or directory
21 | #include<Eigen/Dense>
| ^~~~~~~~~~~~~
compilation terminated.
I installed Eigen from: LINK
Any help is appreciated, thanks.
| what helped me is compiling my program with the following command line:
g++ -I /path/to/eigen/ my_program.cpp -o my_program
It's not efficient but there is a way around it I believe.
|
72,595,888 | 72,599,005 | How to manipulate large Eigen matrices with functional programming in C++? | When dealing with large data structure, I always prefer to pass a buffer by references in order to manipulate it from a function. However, in functional programming this is forbidden because of the use of pure functions.
How would it be possible to implement a function in C++ like
value(const Eigen::VectorXd& _input, Eigen::MatrixXd& _large_matrix_output);
with a functional programming style?.
In fact, the problem with implementing that as a pure function is the instantiation/allocation. The next example will allocate memory each time
Eigen::MatrixXd value(const Eigen::VectorXd& _input);
I thought in the following alternative. But will will require to reize the matrix each time the input changes.
class value{
private:
mutable Eigen::MatrixXd result;
public:
Eigen::MatrixXd &operator()(const Eigen::VectorXd& _input) const{
//... body
return result;
}
};
| It seems like you are asking the impossible: How to access an existing buffer without passing that buffer.
There are a few options that go into that direction but I'm pretty sure you won't like them:
1 Just give up
Eigen::MatrixXd value(const Eigen::Ref<const Eigen::VectorXd>&) will cause a new allocation, which you may then copy into a larger allocation. So it will be slower than it needs to be (much so with very large allocations). But it will be clean, simple, and the code within the function will be well optimized.
The compiler will not optimize this allocation away. They are not magical.
2 Convert your function into a CwiseNullaryOp as described in the documentation
The idea is to return a custom Eigen expression that you can then assign to the large buffer. Especially since nullary ops basically wrap C++ lambdas (or functor structs) they allow a very functional coding style.
However, they also take away much of Eigen's optimization potential because they just compute a single scalar per call, not a CPU vector package. Basically, at this point we rely on the compiler optimizations and whatever can be optimized within a single evaluation.
Something like this should work:
inline auto value(const Eigen::Ref<const Eigen::VectorXd>& vec)
{
Eigen::Index rows = vec.size(), cols = vec.size();
return Eigen::MatrixXd::NullaryExpr(rows, cols,
[=](Eigen::Index row, Eigen::Index col) -> double {
return vec[row] * vec[col];
});
}
Eigen::MatrixXd buf(...);
buf.middleRows(...) = value(...);
buf = value(...).middleRows(...);
Note that this type of code makes it very easy to rely on dangling pointers. That lambda is still referencing the passed vector. Better hope you finish using that new expression before the vector is deallocated. This is especially concerning with Eigen::Ref because that can contain a temporary allocation, for example if you pass a row of a column-major matrix.
Better write it like this:
template<class Derived>
auto value(const Eigen::MatrixBase<Derived>& vec)
{
Eigen::Index rows = vec.size(), cols = vec.size();
return Eigen::MatrixXd::NullaryExpr(rows, cols,
[=](Eigen::Index row, Eigen::Index col) -> double {
return vec[row] * vec[col];
});
}
3 Return Eigen expressions
You can improve on version 2 by writing fully fledged Eigen expressions of your own. But writing them with vectorization is basically undocumented. You have to inspect the source code of Eigen and follow their pattern.
An easier approach is to rely on the return value deduction I also used above and simply return Eigen's expression.
template<class Derived>
auto value(const Eigen::MatrixBase<Derived>& vec)
{ return vec * vec.transpose(); }
buf.noalias() = value(...);
Note that this also does not allocate a matrix and evaluate the result into it. It returns an expression that can be evaluated into a matrix. So you better get the lifetime of of your objects right.
For example, if you cannot spot what is wrong with the following code, this style of programming is not for you.
template<class Derived>
auto value(const Eigen::MatrixBase<Derived>& vec)
{
Eigen::RowVector3d tmp(1., 2., 3.);
return vec * tmp;
}
Final thoughts
All of this may make your function interfaces look nicer (or worse). As far as writing pure functions goes, it just -- at best -- moves the ugly parts into Eigen. It doesn't eradicate them.
From a practical and performance point of view, the original version, where you passed the output buffer into the function is still usually the best unless you want to do crazy complicated mixing and matching between your matrix expressions.
void value(const Eigen::Ref<const Eigen::VectorXd>& in, Eigen::Ref<Eigen::MatrixXd> out);
|
72,596,785 | 72,596,870 | Cannot find a logical sense | i already studied c++ in school and during the last days i have been doing the beginner c++ course of codecademy. On codecademy there is an exercise in which i have to identify palindrome words and return true or false. I haven't been able to resolve it so i saw the solution and it was:
#include <iostream>
// Define is_palindrome() here:
bool is_palindrome(std::string text) {
std::string reversed_text = "";
for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
}
if (reversed_text == text) {
return true;
}
return false;
}
int main() {
std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("ada") << "\n";
std::cout << is_palindrome("lovelace") << "\n";
}
My only doubt is with this line:
for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
i know it has to do with index values but i can't understand why it has a -1.
Could somebody explain this to me?
i thanks in advance whoever read this post. i'm sorry for my english or my poor using of stacksoverflow, i'm italian and that's my first time using this site.
| for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
text is basically the string that you receive as input via function. size() is function that returns the size of the string i.e text.size() so in our test cases it will return
5 for madam
3 for ada
8 for lovelace
If you think about the strings as an array with exact above size then the index range will become
0-4 for madam
0-2 for ada
0-7 for lovelace
So that's why the text.size()-1 is using as the starting index of loop. text.size() will return the actual size of string and then minus 1 to get the index of last character in string.
so behind the scene, your loop iteration will look something like below
for (int i = 4; i >= 0; i--) { //for madam
}
//aca
for (int i = 2; i >= 0; i--) {
}
//lovelace
for (int i = 7; i >= 0; i--) {
}
I hope it clear out your confusion.
Thanks,
|
72,596,946 | 72,627,348 | QGraphicsScene doesn't removeItem() immediately | I have a simple node graph editor in c++/Qt that uses QGraphicsView/QGraphicsScene to draw the graph and I'm experiencing a weird issue where QGraphicsItems sometimes remain on the scene for a split second after calling scene.removeItem(Item). I'm deleting the the items right after removing them from the scene so it's causing segfaults. When I comment the deletion out I can see a part of the item being drawn (not the whole thing) for a literal second before it disappears completely.
Here's my code. It's a slot that gets called by a when a connection gets removed.
void GraphScene::connectionRemoved(QUuid uuid)
{
//Connections and nodes are stored in QMaps to retrieve them by uuid
ConnectionGraphicsItem *connectionItem = connections.value(uuid);
if (connectionItem == nullptr) return;
removeItem(connectionItem); //Delayed
//delete connectionItem;
qDebug() << "con removed" << uuid;
}
I tried calling prepareGeometryChange() before removing the item from the scene and it didn't fix it. Setting QGraphicsView update mode to FullViewportUpdate didn't help either.
| I've solved the problem.
Qt Docs for
void QGraphicsItem::prepareGeometryChange()
state that you need to call this method before changing the bounding rectangle of the item so that the graphics scene updates its index. I didn't do this. So when I added this before the code that adjusts the connections to match node ports the problem disappeared.
Edit: Also, I've realized that I don't remove the item from the QMap.
|
72,597,185 | 72,606,213 | Xcode cannot find cstdint included in bridging header | I am building an iOS app in Swift using Swift UI. This app needs to call C++ code available through a static lib. So, I've setup my Swift code to call an Objective C bridging layer that in turn calls the C++ code. It mostly works ok i.e. I am able to make calls to my own C++ library.
Except I am not able to include a number of standard C++ headers (like cstdint) in any of my header files that are imported into the Bridging header. A few relevant things I checked in this investigation:
I am able to import stdint.h (older version of the header?) just fine, but if I include cstdint, the preprocessing of the bridging header fails, saying that it cannot find cstdint.
I am able to import cstdint in my .mm files without issue.
Apple Clang - Language C++ > C++ Language dialect is set to "GNU++17 [-std=gnu++17].
Apple Clang - Language C > C language dialect is "gnu11".
Build options > Compiler for C/C++/Objective C is set to Default compiler (Apple Clang).
Any clues as to what I must update in my project build settings, or any flags I need to pass in?
| TIL (from elsewhere), that my Objective C shim header file for the C++ code, cannot include C++ headers like cstdint because there is no C++ parsing in the swift compiler. Including stdint.h worked because that is a C header.
|
72,597,256 | 72,597,286 | Why I can't use constructor initializer list to initialize a in-class struct? | I'm trying to do this:
class test{
public:
struct obj{
int _objval;
};
obj inclassobj;
int _val;
test(){}
test(int x):_val(x){}
test(int x, int y): _val(x), inclassobj._objval(y){}
};
It doesn't work. Unless I put in-class struct part in to the body of the constructor like this:
test(int x, int y){
_val = x;
inclassobj._objval = y;
}
This way works fine. Then I find someone said unless I can give my in-class object it's own constructor, then I did this, it doesn't work:
class test{
public:
struct obj{
int _objval;
obj(){}
obj(int val): _objval(val){}
};
obj inclassobj(6);
};
The error pops up at the line where I'm trying to instantiated obj: obj inclassobj(6);
I have totally no idea about this. The first question is why I can't use constructor initializer list to initialize a in-class struct in this case? If the reason is I need to give that struct a constructor, why the second part is also doesn't work?
update::
I realize I can use a pointer to initialize the in-class object like this:
class test{
public:
struct obj{
int _objval;
obj(){}
obj(int val): _objval(val){}
};
obj* inclassobj = new obj(6);
};
But why?
| In your 2-param constructor, you can use aggregate initialization of the inner struct, eg:
test(int x, int y): _val(x), inclassobj{y}{}
Online Demo
In your second example, adding a constructor to the inner struct is fine, you just need to call it in the outer class's constructor member initialization list, eg:
test(int x, int y): _val(x), inclassobj(y){}
Online Demo
|
72,597,513 | 72,597,529 | Converting an integer to Char Pointer using C | I am trying to convert an integer to a char pointer as shown below. The data results are different. I am not sure what is going wrong. Please help me in correcting the code.
int main(){
char *key1 = "/introduction";
std::ostringstream str1;
str1<< 10;
std::string data=str1.str();
std::cout <<"The data value="<<data<<std::endl; // The data value= 10
char *intro= new char[data.length()+1];
strcpy(intro, data.c_str());
std::cout <<"The data value="<<*intro <<std::endl; // The data value=1
return 0;
}
I am not sure why two data value are printed different i.e, 10 and 1.
| In C++, when trying to print all the contents of a char * with cout, you should pass the pointer, i.e. cout << intro << endl.
What you've done here is dereferenced the char *, so cout << *intro << endl is equivalent to cout << intro[0] << endl, which is equivalent to printing the first character, 1.
|
72,598,253 | 72,601,919 | Why can std::function bind functions of different types? | I saw a special usage about std::bind(), just like the following code:
using namespace std::placeholders;
class Test {
public:
Test() {
_state_function_map[0] = std::bind(&Test::state_function, _1, _2);
}
void test_function() {
auto it = _state_function_map.find(0);
int result = it->second(this, 0.0);
}
private:
int state_function(const double value) const {
// do someting
}
private:
using func_type = std::function<int(Test* const, const double)>;
std::unordered_map<int, func_type> _state_function_map;
};
What I can't understand is, func_type and Test::state_function are not the same type, func_type has two parameters, and Test::state_function only has one parameter, so why can they bind Test::state_function in _state_function_map?
|
func_type has two parameters, and Test::state_function only has one parameter,I can't understand how it works.
For binding purposes, the non-static member function state_function has an additional first implicit object parameter of type const Test&.
Now, when we define a std::function object, we specify the function type that is the signature of the callable object that object can represent. When the callable is a member function, the signature’s first parameter represent the (normally implicit) object on which the member function will be called on. Now, there are two ways to specify the signature in case of a member function:
Method 1
Here we say that the object on which the member function will be called will be passed as a pointer.
//----------------------------------vvvvv-------------------------->pointer here means a pointer to the object of type `Test` will be passed
using func_type = std::function<int(Test* const, const double)>;
This method 1 is what you used in your example. It means that the member function was being called using a pointer to an object of type Test.
Method 2
But there is another way of passing the object. In particular, you can sepcify that the object will be passed as a reference as shown below:
//----------------------------------------vvvvv------------------>note the reference here which says that here an object of type `Test` will be passed instead of a pointer
using func_type = std::function<int(const Test&, const double)>;
Note also that for the above to work you will have to modify it->second(this, 0.0); to
//---------vvvvv-------------->note the * used here to dereference
it->second(*this, 0.0);
Demo
|
72,598,429 | 72,599,699 | Exception with OpenCV4.5.5 DnnSuperResImpl - ReadModel (C++) | I have a issue when using OpenCV dnn module.
Here are my settings:
Building OpenCV 4.5.5 with extra module opencv_contrib-4.x (clone from github)
Downloading EDSR_x4.pb and EDSR_x3.pb from EDSR_tensorflow
move .pb files to root directory of my project
However, no matter I used relative path or absolute path, readModel() failed for these two path:
DnnSuperResImpl sr;
sr.readModel ("EDSR_X4.pb");
sr.readModel ("C:\\Users\\user\\source\\repos\\ZBAR_OpenCV4.5\\ZBAR_OpenCV4.5\\EDSR_x3.pb");
Results from using command "dir"
C:\Users\user\source\repos\ZBAR_OpenCV4.5\ZBAR_OpenCV4.5
2022/06/13 afternoon 01:39 201,562 EDSR_x3.pb
2022/06/13 afternoon 10:40 206,908 EDSR_x4.pb
2022/06/07 afternoon 11:37 3,124 ZBAR_OpenCV4.5.cpp
2022/06/07 afternoon 11:37 544 ZBAR_OpenCV4.5.h
2022/06/13 afternoon 02:05 8,719 ZBAR_OpenCV4.5Dlg.cpp
2022/06/13 afternoon 11:37 1,627 ZBAR_OpenCV4.5Dlg.h
Exception printed out:
code= -2
err= FAILED: ReadProtoFromBinaryFile(param_file, param) Failed to parse GraphDef file: EDSR_x4.pb
func= cv::dnn::ReadTFNetParamsFromBinaryFileOrDie
line= 42
msg= OpenCV(4.5.5) C:\OpenCV4.5\opencv\sources\modules\dnn\src\tensorflow\tf_io.cpp:42: error: (-2:Unspecified error) FAILED: ReadProtoFromBinaryFile(param_file, param). Failed to parse GraphDef file: EDSR_x4.pb in function 'cv::dnn::ReadTFNetParamsFromBinaryFileOrDie'
what= OpenCV(4.5.5) C:\OpenCV4.5\opencv\sources\modules\dnn\src\tensorflow\tf_io.cpp:42: error: (-2:Unspecified error) FAILED: ReadProtoFromBinaryFile(param_file, param). Failed to parse GraphDef file: EDSR_x4.pb in function 'cv::dnn::ReadTFNetParamsFromBinaryFileOrDie'
| The solution is really simple.
Just check if the integrity of EDSR_x4.pb is a pb file or a html, and I incorrectly used the later.
So, I download from the github again, and it worked.
|
72,598,498 | 72,599,350 | Behaviour of friend function template returning deduced dependent type in class template | I've happened across the following code, the behaviour of which is diagreed upon by all of GCC, Clang, and MSVC:
#include <concepts>
template<typename T>
auto foo(T);
template<typename U>
struct S {
template<typename T>
friend auto foo(T) {
return U{};
}
};
S<double> s;
static_assert(std::same_as<decltype(foo(42)), double>);
Live demo: https://godbolt.org/z/hK6xhesKM
foo() is declared at global namespace with deduced return type. S<U> provides a definition for foo() via a friend function, where it returns a value of type U.
What I expected is that when S is instantiated with U=double, its definition of foo() gets put in the global namespace and U is substituted in, due to how friend functions work, effectively like this:
template<typename T>
auto foo(T);
S<double> s;
template<typename T>
auto foo(T) {
return double{};
}
Thus I expect foo()'s return type is double, and the following static assertion should pass:
static_assert(std::same_as<decltype(foo(42)), double>);
However, what actually happens is that all three compilers disagree on the behaviour.
GCC passes the static assertion, like I expect.
Clang fails the static assertion, as it seems to believe that foo() returns int:
'std::is_same_v<int, double>' evaluated to false
And MSVC produces a different error entirely:
'U': undeclared identifier
I find it bizarre that all the compilers have different behaviour here for a seemingly simple code example.
The issue does not occur if foo() isn't templated (see demo here), or if it doesn't have deduced return type (see demo here).
Which compiler has the correct behaviour? Or, is the code ill-formed NDR or undefined behaviour? (And, why?)
|
Which compiler has the correct behaviour? Or, is the code ill-formed NDR or undefined behaviour? (And, why?)
As @Sedenion points out in a comment, whilst touching upon the domain of CWG 2118 (we'll return to this further down) this program is by the current standard well-formed and GCC is correct to accept it, whereas Clang and MSVC are incorrect to reject it, as governed by [dcl.spec.auto.general]/12 and /13 [emphasis mine]:
/12 Return type deduction for a templated entity that is a function or function template with a placeholder in its declared type
occurs when the definition is instantiated even if the function body contains a return statement with a non-type-dependent operand.
/13 Redeclarations or specializations of a function or function template
with a declared return type that uses a placeholder type shall also
use that placeholder, not a deduced type. Similarly, redeclarations or
specializations of a function or function template with a declared
return type that does not use a placeholder type shall not use a
placeholder.
[Example 6:
auto f();
auto f() { return 42; } // return type is int
auto f(); // OK
// ...
template <typename T> struct A {
friend T frf(T);
};
auto frf(int i) { return i; } // not a friend of A<int>
Particularly the "not a friend of A<int>" example of /13 highlights that the redeclaration shall use a placeholder type (frf(T), and not a deduced type (frf(int)), whereas otherwise that particular example would be valid.
/12, along with [temp.inst]/3 (below) covers the that return type deduction for the friend occurs only after the friend's primary template definition has been made available (formally: it's declaration but not definition has been instantiated) from the instantiation of the S<double> enclosing class template specialization.
The implicit instantiation of a class template specialization causes
(3.1) the implicit instantiation of the declarations, but not of the definitions, of the non-deleted class member functions, member
classes, scoped member enumerations, static data members, member
templates, and friends; and
[...]
However, for the purpose of determining whether an instantiated
redeclaration is valid according to [basic.def.odr] and [class.mem], a
declaration that corresponds to a definition in the template is
considered to be a definition.
[Example 4:
// ...
template<typename T> struct Friendly {
template<typename U> friend int f(U) { return sizeof(T); }
};
Friendly<char> fc;
Friendly<float> ff; // error: produces second definition of f(U)
— end example]
CWG 2118: Stateful metaprogramming via friend injection
As covered in detail e.g. in A foliage of folly, one can rely on the single first instantiation of a class template to control how the definition of a friend looks like. First here means essentially relying on meta-programming state to specify this definition.
In OP's example the first instantiation, S<double>, is used to set the definition of the primary template of the friend foo such that its deduced type will always deduce to double, for all specializations of the friend. If we ever (in the whole program) instantiate, implicitly or explicitly, a second instantiation of S (ignoring S being specialized to remove the friend), we run into ODR-violations and undefined behavior. This means that this kind of program is, in practice, essentially useless, as it would serve clients undefined behavior on a platter, but as covered in the article linked to above it can be used for utility classes to circumvent private access rules (whilst still being entirely well-formed) or other hacky mechanisms such as stateful metaprogramming (which typically runs into or beyond the grey area of well-formed).
|
72,598,746 | 72,812,603 | In google benchmark, what is the meaning of Iterms_per_seconds and Why we need fixture? | In google benchmark:
there is a Iterms_per_seconds result and we can use the fixture way to test the bench.
What is the meaning of Iterms_per_seconds in google bench? Is it stands the throuput?
Why need the fixture to test benchmark? In this way , can we get more convenience?
|
items per second is the throughput. items is defined by the benchmark author and is completely optional. the benchmark author can also define bytes processed for bytes per second, if that is more meaningful.
you don't need fixtures, but they provide a way to do one-off setup and teardown.
|
72,599,064 | 72,600,213 | Capturing boost::asio::thread_pool in lambda function | I'm trying to capture thread_pool object in a lambda function. This lambda function is called inside a thread. Upon this call, it creates(obtains) a new thread with asio::post. However, it throws segmentation fault. I tried create weak ptr with shared_ptr<thread_pool> but it didn't work as well. Simple example written below,
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>
void thread1(std::function<void()> createThread) {
createThread();
}
void thread2() {
cout << "You made it" << std::endl;
}
int main(int argc, char **argv) {
boost::asio::thread_pool pool(std::thread::hardware_concurrency());
std::function<void()> createThread;
createThread = [&pool] () {
boost::asio::post(pool, boost::bind(thread2));
return true;
};
boost::asio::post(pool, boost::bind(thread1, createThread));
pool.join();
}
It works if I create another thread_pool object inside the lambda function. However, this is not the right way to do this. Therefore, I am open for your suggestions.
Edit: Added libraries to code snippet and removed while loop.
| I'd simplify:
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>
void thread1(std::function<void()> createThread) {
createThread();
while (true) {
std::cout << "Sleeping" << std::endl;
sleep(1);
}
}
void thread2() { std::cout << "You made it" << std::endl; }
int main() {
boost::asio::thread_pool pool;
post(pool,
boost::bind(thread1, [&pool]() { post(pool, boost::bind(thread2)); }));
pool.join();
}
Note the endl that forces stdout to flush, which helps getting results you can expect.
HOWEVER
There's a code smell with:
using explicit "threads" when using a thread-pool
nullary bind expressions
createThread doesn't (create a thread)
passing references to execution contexts. Instead, pass executors
Applying these:
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>
using Executor = boost::asio::thread_pool::executor_type;
void task_loop(Executor ex, std::function<void()> task) {
while (true) {
post(ex, task);
sleep(1);
}
}
void task_function() { std::cout << "Task executes" << std::endl; }
int main() {
boost::asio::thread_pool pool;
post(pool, boost::bind(task_loop, pool.get_executor(), task_function));
pool.join();
}
Prints each second:
Task executes
Task executes
...
|
72,599,099 | 72,601,223 | efficiently updating inplace certain blocks of a large sparse matrix in Eigen? | Suppose that I have a large sparse matrix with the following pattern:
the number of nonzeros per column and their locations are fixed
only matrix block A and B will change and the rest of the matrix stays static; (blocks A and B themselves are also sparse with fixed nonzero locations)
As instructed in the document, i've initialized the above matrix by
reserving the exact number of nonzeros per column for the column major sparse matrix
inserting column by column
inserting from the smallest row index per column
In later part of the program, it's natural to reuse the matrix and only updates the A, B blocks inplace. Possible ways are:
accessing existing entries by coeffRef, would introduce binary search so not preferred here.
iterating over the outer and inner dimensions as documented here
However, it seems a bit unnecessary to iterate over all nonzero entries since most part of the sparse matrix stays the same.
Is it possible to update A, B inplace without iterating over all nonzeros in the matrix?
| From what I can tell, the InnerIterator can be used used for this and runs in constant time.
Eigen::Index col = 1;
Eigen::Index offset_in_col = 1;
using SparseMatrixD = Eigen::SparseMatrix<double>;
SparseMatrixD mat = ...;
SparseMatrixD::InnerIterator i =
SparseMatrixD::InnerIterator(mat, col) + offset_in_col;
assert(i.row() == 1);
assert(i.col() == 1);
assert(i.value() == C);
This should access the value C. All you need to know is how many nonzero elements are per column (or inner dimension in general). You don't need to know how many nonzero columns (outer dimensions) are stored because that array (SparseMatrix.outerIndexPtr()) has one entry per column.
|
72,599,809 | 72,600,078 | Downloading my programs data from a webserver (Its basically just a .exe turned into .txt) but when I put it into a .exe it does not run? | So currently I am using a basic Http request to pull the exe data from my server weblink.com/Program.exe
it returns my program in .txt form but when I put it into a file it will not run.
I assume this is because I need metadata but have no clue how to find that process or even how to google something as specific as that... So I am either asking for a solution (how to add proper .exe metadata) or if there is a better way to download files like that in C++
*Note I cannot use basic windows functions such as DownloadToFileA or External Library's (Like LibCurl/Curl)
OutFile.open(XorStr("C:\\Users\\Program.exe").c_str(), std::ios::out);
if (OutFile.is_open())
{
OutFile << Output;
//Initialize .exe Meta Data???
}
OutFile.close();
| You need to open your file in binary mode otherwise newline translation will screw up your executable:
OutFile.open(XorStr("C:\\Users\\Program.exe").c_str(), std::ios::out | std::ios::binary);
|
72,599,825 | 72,600,031 | compiler error with C++ template says that is not the member of struct | I'm a newer of using C++ template and I got trouble with template compiling.
I want to write a similar factory method with template but compiler error says that 'ip is not the member of _FileWriterInfo'. I was confused because it has be defined in NetWriterInfo struct but not in FileWriterInfo. And if I cancel the 'ip' member defination, compiler works. Apparently T param of NetWriter may infer to FileWriterInfo struct by mistake. How can I get rid of it? plz help.
#include <iostream>
#include <string>
enum WriterFormat
{
WTYPE_FILE = 0,
WTYPE_NET = 1
};
typedef struct _FileWriterInfo
{
std::string name;
std::string page;
}FileWriterInfo;
typedef struct _NetWriterInfo
{
std::string name;
std::string ip;
}NetWriterInfo;
template<typename T>
class Writer
{
public:
virtual ~Writer() {}
virtual std::string Write(T info) = 0;
};
template<typename T>
class FileWriter : public Writer<T>
{
public:
std::string Write(T info) override {
std::cout << "name:" << info.name << "\n";
std::cout << "page:" << info.page << "\n";
return info.name;
}
};
template<typename T>
class NetWriter : public Writer<T>
{
public:
std::string Write(T info) override {
std::cout << "name:" << info.name << "\n";
std::cout << "ip:" << info.ip << "\n";
return info.name;
}
};
class Creator
{
Creator() {};
public:
template<typename T>
static Writer<T>* CreateWriter(WriterFormat fmt)
{
Writer<T>* p = nullptr;
if (fmt == WTYPE_FILE)
p = new FileWriter<T>;
if (fmt == WTYPE_NET)
p = new NetWriter<T>;
return p;
}
};
void WriteFile()
{
FileWriterInfo info = { "Hello","100" };
Writer<FileWriterInfo>* w = Creator::CreateWriter<FileWriterInfo>(WTYPE_FILE);
w->Write(info);
return;
}
int main()
{
WriteFile();
return 0;
}
| The CreateWriter function instantiates the FileWriter and NetWriter classes with the FileWriterInfo structure. Accordingly, the compiler tries to instantiate the NetWriter::Write function with the type FileWriterInfo, and we get an error.
You can place Write methods directly to FileWriterInfo and NetWriterInfo stuctures (according to the principle of data encapsulation). It also can simplify the code.
|
72,600,182 | 72,600,601 | How to draw an arc between known points to draw XNOR gate in Qt? |
I want to draw an arc between point E to point G , F to H ( I want to draw XNOR gate symbol )
I tried this way
path.moveTo(72,10); // for E --> G
QRect bound1 (52,10,20,60);
path.arcTo(bound1,90,-180);
QPainterPath path1; // for F --> H
path1.moveTo(104,10);
QRect bound2 (72,10,32,60);
path1.arcTo(bound2,90,-180);
and it is currently looking like this.
| I think the problem is your QRect. Your hand-drawn picture has the arc E--->G to the right of X coordinate 72. But QRect bound1 starts at 52, not 72. Per the docs
Creates an arc that occupies the given rectangle ...
Note that this function connects the starting point of the arc to the current position if they are not already connected.
You don't want the connection part; you just want the arc itself. So the rectangle for E-H must have E and H as the top-left and bottom-left corners.
|
72,600,207 | 72,600,382 | c++11 std::notify_all and spurious wakeup | with c++11.
As std::notify_all would cause spurious wakeup, then why std::notify_all is remained but not std::notify_one all the time?
And could std::notify_one cause spurious wakeup by the way?
elaborating my doubts:
When I call std::condition_variable.wait/wait_for/wait_until and std::notify_XXX, my purpose is generally to implement thread sychronisation. That is to say, more threads blocked to wait until another thread to notify only one of them to unblock.
Then I can just call notify_one to achieve that, but why there's another notify_all, what is its purpose, or what situation is notify_all suitable for?
And in my situation, when I call notify_all, it will wakeup all waiting threads, then only one thread actually unblock and others remains blocking, is it called spurious wakeup?
And if notify_one would call spurious wakeup as well?
| On void std::condition_variable::wait(std::unique_lock<std::mutex>& lock); from
thread.condition/8.3:
The function will unblock when signaled by a call to notify_one() or a call to notify_all(), or spuriously.
So calling notify_one() or notify_all() is not a prerequisite. It can unblock without any of those being called.
The above quote is from "C++20 first post-publication draft" but has remained the same since it was first written for C++11.
why there's another notify_all, what is its purpose, or what situation is notify_all suitable for?
When you want all waiting threads to unblock. A practical situation would be when it's time to shutdown. If you have threads blocked in a wait they will never finish and join()ing them will hang.
Example with a predicate saying that it should wait until either aborted is true or queue.empty() is false:
bool pop_from_queue(T& item) {
std::unique_lock<std::mutex> lock(mtx);
while(queue.empty() && not aborted) cv.wait(lock);
if(aborted) return false; // time to shutdown
// else pick an item from the queue
item = std::move(queue.front());
queue.pop();
return true;
}
When it's time to shutdown, another thread would here typically do:
aborted = true; // std::atomic<bool>
cv.notify_all();
when I call nitify_all, it will wakeup all waiting threads, then only one thread actually unblock and others remains blocking, is it called spurious wakeup?
No. A spurious wakeup is a wakeup that can happen at any time. If you call notify_all, the waiting threads will all wakeup as ordered - not spuriously.
And if notify_one would call spurious wakeup as well?
It may cause a spurious wakeup, but that would be an implementation detail. The best thing is to just live with the fact that the threads may wakeup at any time and just check the predicate when they do.
could I precislly control where to unblock in the waiting thread(who called condition_variable.wait with no Predicate)?
Without checking the predicate, the only thing the thread knows for sure is that it woke up. It does not now if it's for the right reason or not.
|
72,601,518 | 72,606,581 | Rabin-Miller-Prime test | It runs perfectly but when the numbers are 6 digits and more it "crashes". I have no idea why it doesn't work. I also haven't tried a lot of things to fix it because i don't no where to begin. I know, the test has some weaknesses, I already did some research. There are certain numbers, that cant be detected by the test, but they should be filtered out, when you increase the accuracy
bool testPrime(int primenumber_1)
{
bool even_number_checker = false;
bool prime;
int counter = 0;
int primenumber_mod = 0;
int variable_1 = 1;
int variable_2 = 1;
primenumber_mod = primenumber_1 - 1;
if(primenumber_1 % 2 == 0) return false;
while(primenumber_mod%2 == 0)
{
primenumber_mod/=2;
}
if(even_number_checker == false && primenumber_1 != 43405 && primenumber_1 != 27905)
{
variable_1 = (int)pow(2, primenumber_mod) % primenumber_1;
if(variable_1 != 1 && variable_1 != -1)
{
while(variable_1 + 1 != primenumber_1 &&
variable_1 - 1 != primenumber_1 &&
variable_2 + 1 != primenumber_1 &&
variable_2 -1 != primenumber_1)
{
if(counter >= 40) break;
variable_2 = (int)pow(variable_1, 2) % primenumber_1;
variable_1 = variable_2;
counter++;
}
prime = (variable_1 + 1 == primenumber_1 ||
variable_2 + 1 == primenumber_1);
}
}
return prime;
}
int primeGenerator()
{
int number = rand()%999900+100000;
while(!testPrime(number))
{
number = rand()%899000+100000;
}
return number;
}
bool testPrimeSafe(int number)
{
for(int i = 2; i < number; i++)
{
if(number % i == 0)
{
return false;
}
}
return true;
}
void testTestPrime()
{
for(int i = 0; i < 10000; i++)
{
int prime = primeGenerator();
if(testPrimeSafe(prime))
{
std::cout << "\e[32;42mSUCCESS :: " << prime << "\e[0m\n";
}
else
{
std::cout << "\e[48;5;196;1m*EVIL MORTY THEME PLAYING* :: " << prime << "\e[0m\n";
}
}
}
int main()
{
srand(time(NULL));
testTestPrime();
}
| Well (int)pow(2, primenumber_mod) will overflow a signed 32-bit integer if primenumber_mod is greater than 31. If the input is a 6-digit integer it is very likely primenumber_mod will be much larger than that.
|
72,602,548 | 72,603,200 | Strange compilation errors when instantiating a variadic function template | Let's first introduce a helper type that represents a parameter pack:
template<typename... T> struct Pack { };
Now, here's the function with the weird behaviour:
template<typename... TT, typename T>
void f(Pack<TT...>, Pack<T>, std::type_identity_t<TT>..., std::type_identity_t<T>);
std::type_identity_t is used here to disable deduction from the last two parameters in case that would introduce any ambiguity.
First, I tried to call it like so:
f(Pack<int>{}, Pack<int>{}, 5, 5);
GCC raises an error and gives the following explanation:
<source>:12:6: note: candidate expects 3 arguments, 4 provided
12 | f(Pack<int>{}, Pack<int>{}, 5, 5);
| ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
That's not the kind of error I expected, I assumed that deduction would result in T = int and TT... = int. But okay, let's do what the note says and provide one less argument:
f(Pack<int>{}, Pack<int>{}, 5);
It still gives an error, but this time it's:
<source>:12:6: error: too few arguments to function 'void f(Pack<TT ...>, Pack<T>, std::type_identity_t<TT>..., std::type_identity_t<T>) [with TT = {int}; T = int; std::type_identity_t<T> = int]'
10 | f(Pack<int>{}, Pack<int>{}, 5);
| ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now it's too few of them. Also notice that this error message confirms my assumption about the deduced T and TT....
At this point I switched to Clang to see whether it'd compile this code, but both of the above calls to f (with 3 and 4 arguments) result in the same error, with the note:
<source>:8:6: note: candidate template ignored: deduced packs of different lengths for parameter 'TT' (<int> vs. <>)
void f(Pack<TT...>, Pack<T>, std::type_identity_t<TT>..., std::type_identity_t<T>);
^
I also tried compiling the code with MSVC, and it did compile without errors.
What is going on? Is there something that makes this code invalid? Is it a compiler bug, due to the strange error messages?
| std::type_identity<TT>... is mentioned in the comments as an way to remove the third function parameter (which is a pack) from argument deduction, but this has no effect as a function parameter pack that does not occur at the end of a parameter list is in a non-deduced context anyway; as per [temp.deduct.type]/5.7:
/5 The non-deduced contexts are:
[...]
/5.7 A function parameter pack that does not occur at the end of the parameter-declaration-list.
Then why can't the parameter pack be unambiguously deduced from the first function parameter (Pack<TT...>)? This would arguably make sense for C++ developers, however it may end up as a quality of implementation issue for implementors, as it would start mixing template argument deduction with overload resolution. It would require two-pass template argument deduction where first a parameter pack is unambigously deduced whereafter from say one function parameter, after which the result is used to modify the same function's parameter list (to expand an otherwise non-deducible parameter pack) and thereafter return to template argument deduction for the modified function template. This is not how template argument deduction works anywhere else, possibly solely due to quality of implementation.
[temp.deduct.call]/1 does mention that such a pack is never deduced (emphasis mine):
[...] When a function parameter pack appears in a non-deduced context ([temp.deduct.type]), the type of that pack is never deduced.
It could be argued whether or not this intentionally rejects packs that could be deduced from anywhere else. If so, the OP's program is indeed ill-formed, however the error messages of the compilers is not very helpful in diagnosing this as the root cause (if it it). It seems as if compilers may rely on [temp.deduct.call]/1 to actually deduce non-deducible template parameter packs to empty packs.
We may finally note that [temp.deduct.call]/1 supports the use of explicit template arguments, as this is not deduction:
#include <type_traits>
template<typename... T> struct Pack { };
// Note the swap of template argument positions
// to allow explicitly providing template arguments.
template<typename T, typename... TT>
void f(Pack<TT...>, Pack<T>, std::type_identity_t<TT>..., std::type_identity_t<T>) {}
int main() {
f<int, int, int>(Pack<int, int>{}, Pack<int>{}, 1, 2, 3);
}
|
72,603,357 | 72,603,454 | unique_ptr can't instantiate class because it's abstract | I have an abstract class(Component)
and this class should be owned by another class(GameObject).
Every GameObject has a vector of components.
Header:
class Component;
class GameObject{
public:
GameObject();
virtual ~GameObject();
void addComponent(std::unique_ptr<Component> component);
void addComponent(Component* component);
void removeComponent(std::unique_ptr<Component> component);
virtual void update();
std::string getInfo();
//return the first component of type T
template<typename T>
T* getComponent(){
for(auto& component : components){
if(dynamic_cast<T*>(component.get())){
return dynamic_cast<T*>(component.get());
}
}
return nullptr;
}
// return the component with the type T
template<typename T>
std::vector<T*> getComponents(){
std::vector<T*> components;
for(auto component : this->components){
if(dynamic_cast<T*>(component)){
components.push_back(dynamic_cast<T*>(component));
}
}
return components;
}
std::vector<std::unique_ptr<Component>> components;
};
class Component
{
private:
public:
Component() = delete;
virtual ~Component() = 0;
virtual std::string getInfo();
//the game object this component is attached to
GameObject* gameObject;
};
source:
std::string GameObject::getInfo() {
std::stringstream ss;
ss << typeid(*this).name();
for (Uint32 i = 0; i < this->components.size(); i++) {
ss << typeid(components[i]).name() << " " << this->components[i]->getInfo();
}
}
void GameObject::addComponent(std::unique_ptr<Component> component) {
components.push_back(std::move(component));
}
void GameObject::addComponent(Component* component) {
components.push_back(std::move(std::make_unique<Component>(*component)));
}
void GameObject::removeComponent(std::unique_ptr<Component> component) {
for (auto it = components.begin(); it != components.end(); it++) {
if (it->get() == component.get()) {
components.erase(it);
return;
}
}
}
ERROR: cannot instantiate abstract class. file: memory line 3416
| Your issue is here:
void GameObject::addComponent(Component* component) {
components.push_back(std::move(std::make_unique<Component>(*component)));
}
When you dereference component, as far as the compiler knows you still just have a Component, not the actual instantiation--it can't call the proper copy constructor.
The solution is to just deleted this member function entirely. You already have a version that takes a std::unique_ptr<Component>, so require the user of GameObject to provide the unique_ptr in all cases.
|
72,603,420 | 72,618,255 | How could tell which way is condition_variable.wait_for unblocked by, spurious wakeup or cv_status::timeout? | As far as I know, only condition_variable.wait_for with predicate(because double check inside) could avoid to be unblocked by spurious wakeup, but not the version without predicate(use if not while).
But what if I want to do something when only cv_status::timeout happened and do something else by notify_XXX?
because condition_variable.wait_for with predicate returns only bool, it cannot tell if it is unblocked by notify_XXX or cv_status::timeout; and although condition_variable.wait_for without predicate returns cv_status::timeout, but it cannot tell if it is unblocked by spurious wakeup or notify_XXX.
| Condition variables are best used as a triple. The cv, the mutex, and the payload.
Without the payload (implicit or explicit), there is no way to determine if the wakeup is spurious or not.
The predicate version makes it easy to check the payload, but in some complex situations checking the payload might be easier without doing it in a lambda. So the other API is provided.
After modifying the payload, the mutex that the condition variable operates on must be in a locked state afterwards before you send signal. (You could guard the payload with the mutex, for example; or you could modify the payload, atomically, then lock and unlock the mutex, then send the signal). Otherwise, the opposite of spurious wakeup (a missed signal) can occur.
All of this is tricky to get right, and easy to accidentally get wrong.
If you want to write new concurrency code (especially using low level primitives), you have to learn enough of the C++ memory model and learn how to prove your algorithms are correct. Because it is way, way to hard to write code and base its correctness based on "does it work".
You have correctly identified that you can't solve this without additional data. You need to add that additional data, and use it to determine if the wakeup was spurious or real. That is by design.
C++ could have added that additional data to condition variable, but then it would have made you pay for it even if you aren't using it. Condition variable is a low level primitive that lets you write code as near to optimal as possible, the fact is it wrapped in a class can be confusing to some people.
And there are lots of payloads. If you have a counting semaphore, where the number of sent signals matches the number of received signals, your payload is going to be an integer. If you have a latch or gate, where once open everyone is free to go through it, your payload is going to be a bool.
struct gate {
void wait_on_gate() const {
auto l = lock();
cv.wait( l, [&]{ return !closed; } );
}
// false iff it times out
template<class Time>
bool wait_on_gate_until(Time time) const {
auto l = lock();
return cv.wait_until( l, time, [&]{ return !closed; } );
}
// false iff it times out
template<class Duration>
bool wait_on_gate_for(Duration d) const {
auto l = lock();
return cv.wait_for( l, d, [&]{ return !closed; } );
}
// Once you call this, nobody waits
void open_gate() {
auto l = lock();
closed = false;
cv.notify_all();
}
private:
mutable std::mutex m;
std::condition_variable cv;
bool closed = true;
};
now you'll note I'm using the lambda version.
We can refactor to the non-lambda version:
void wait_on_gate() const {
auto l = lock();
while(closed)
cv.wait( l );
}
template<class Time>
void wait_on_gate_until(Time time) const {
auto l = lock();
while(closed) {
if (cv.wait_until(l, time) == std::cv_status::timeout)
return !closed;
}
return true;
}
which is more complex, and acts exactly the same. (assuming I have no typos).
The only difference is you could do fancy things that might not fit in a lambda. For example, you could choose to say "well, it was spurious, but while I'm awake I'll go do some bookkeeping somewhere else and come back later".
|
72,604,511 | 72,604,641 | Understanding enable_if implementation in C++98 | I have seen this given as a self-explanatory implementation of enable_if for C++98 :
template<bool b, typename T = void>
struct enable_if {
typedef T type;
};
template<typename T>
struct enable_if<false, T> {};
But alas I personally don't understand it. I don't see where the boolean kicks into play. Would really appreciate if someone would unwrap it for me.
| First consider this:
template<bool b>
struct foo {
static const bool B = b;
};
template <>
struct foo<false> {
static const bool B = false;
};
Its a primary template and a specialization. In the general case foo<b>::B is just b. In the special case when b == false the specialization kicks in and foo<false>::B is false.
Your example of std::enable_if is different for two reasons: A) It is using partial specialization. The specialization is for any type T and b == false;. B) in the specialization there is no type member alias. And thats the whole purpose of std::enable_if. When the condition is false then std::enable_if< condition, T>::type is a substitution failure, because the specialization has no type. When the condition is true then std::enable_if<condition,T>::type is just T.
|
72,605,087 | 72,605,160 | WinEventHook: what happen when the thread that installed the event hook ends? | I did some testing and noticed that when the thread that installed an event hook ends (or is killed) the callback function is no longer called, as if the hook ended together with the thread.
However, the documentation says to call UnhookWinEvent from the same thread that installed the event, which is not possible if the thread is no longer alive.
Therefore, if the thread that installed the event hook terminates unexpectedly before calling UnhookWinEvent, what happens? Does some problem occur? Or does the event hook terminate together with the thread, as if UnhookWinEvent had been called?
| You probably ought to have read that documentation you linked to:
If the client's thread ends, the system automatically calls this
function.
|
72,605,454 | 72,605,972 | Wrap a C++ lambda with another lambda | I am trying to get the contents of a lambda in c++ and creating another function from it. A minimal example that would be ideal is something like:
auto A = []{ some_function(args); };
auto B = []{ return /*Contents of A*/; };
// Ideally this would translate to
auto B = []{ return some_function(args); };
Macros could work, but I would like to avoid them. I have tried a few things but I can't seem to find if there is a way to get the content of a lambda (not only the return it could have), and write code around it. There might not be a way, but I wanted to be sure.
One of the applications of this that I would be curious about is to write a simple unit test as:
Test a = []{
check(1 == 1);
check(2 == 1);
};
And have a wrapper around all test functions that could be like:
[]{
for (line : /*Contents of A*/) {
print("Evaluating {}...", line);
if (not line)
print("Failed test");
}
};
So if A = F1, F2, F3, ..., you can create B(A) = B(F1), B(F2), B(F3), ...
| After C++ code has been compiled, there is no standard way to get information about its source code or modify the source code in the ways you are looking for. Most C++ implementations turn the source code into machine code (i.e. assembly instructions) and run it through an optimizer that can reorder or remove the code as long as the observable behavior of the code is still the same.
The only thing I can think of is very complex and it's not even a complete solution: if you ship your program with a copy of its own source code and all the headers it relies on, then you could link against libclang and use that to parse the C++ source code and get detailed information about every AST node. This would add a lot of complexity to your program so it's probably not worth it.
|
72,605,666 | 72,607,622 | Does the camera face the x axis when the yaw is 0? | so I’ve been reading about the camera in learnopengl and noticed that in the yaw image, it seems as the though camera is facing the x axis when the yaw is 0. Shouldn’t the camera be facing the negative z axis? I attached the image to this message. In the image, the yaw is already a certain amount of degrees but if the yaw is 0, would that mean that the camera is facing the x axis?
| First, let's bring a little bit more context into your question so that we know what your are actually talking about.
We can assume that when you say
so I’ve been reading about the camera in learnopengl
that by this you are specifically referring to the chapter called "Camera" in the https://learnopengl.com/Getting-started/Camera tutorial.
Under the sub-section "Euler angles", there is the image which you are also including in your question.
If you read a little bit further, you'd see the following definition of the direction vector, which that tutorial later uses to build a lookat matrix:
direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
direction.y = sin(glm::radians(pitch));
direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
So, just by looking at that and doing the math, we see that direction will be (1, 0, 0) when yaw and pitch are 0.
But, if we read further, we see this paragraph:
We've set up the scene world so everything's positioned in the direction of the negative z-axis. However, if we look at the x and z yaw triangle we see that a θ of 0 results in the camera's direction vector to point towards the positive x-axis. To make sure the camera points towards the negative z-axis by default we can give the yaw a default value of a 90 degree clockwise rotation. Positive degrees rotate counter-clockwise so we set the default yaw value to:
yaw = -90.0f;
So that is the answer to your question: In the context of that tutorial, by simply its own definition of the direction vector, it will point to (1, 0, 0) when both angles are 0. And to counteract this, that tutorial will assume that the initial value of yaw is -90.
Sure, they could've just used a different formula for the direction vector components to yield (0, 0, -1) as the result when the angles are 0, but they didn't.
|
72,605,722 | 72,607,702 | Eigen Error: static assertion failed C++ after replacing fftw_malloc array with eigen | I am trying to switch my code and start using Eigen library in C++ since I have heard it is really good with matrices. Now my old C++ code used mostly fftw_malloc to initialize my arrays like the following:
static const int nx = 10;
static const int ny = 10;
double *XX;
XX = (double*) fftw_malloc(nx*ny*sizeof(double));
memset(XX, 42, nx*ny* sizeof(double));
for(int i = 0; i< nx; i++){
for(int j = 0; j< ny+1; j++){
XX[j + ny*i] = (i)*2*M_PI/nx;
}
}
So I changed it to the following,
Matrix <double, nx, ny> eXX;
eXX.setZero();
for(int i = 0; i< nx; i++){
for(int j = 0; j< ny+1; j++){
eXX[j + ny*i] = (i)*2*EIGEN_PI/nx;
}
}
This however returns the error:
In file included from /mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/Core:164,
from /mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/Dense:1,
from Test.cpp:21:
/mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/src/Core/DenseCoeffsBase.h: In instantiation of ‘Eigen::DenseCoeffsBase<Derived, 1>::Scalar& Eigen::DenseCoeffsBase<Derived, 1>::operator[](Eigen::Index) [with Derived = Eigen::Matrix<double, 10, 10>; Eigen::DenseCoeffsBase<Derived, 1>::Scalar = double; Eigen::Index = long int]’:
Test.cpp:134:16: required from here
/mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/src/Core/DenseCoeffsBase.h:408:36: error: static assertion failed: THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD
408 | EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime,
| ^~~~~~~~~~~~~~~~~~~~~
/mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/src/Core/util/StaticAssert.h:33:54: note: in definition of macro ‘EIGEN_STATIC_ASSERT’
33 | #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG);
| ^
I see the error is pointing at line: eXX[j + ny*i] = (i)*2*EIGEN_PI/nx;
I am fairly new to Eigen and still trying to understand my way around so any feedback/suggestions would help. Thanks.
| The assertion message THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD already tells you what the error is: Do not use operator[] but instead use operator(), like so:
#include <Eigen/Core>
int main()
{
static const int nx = 10;
static const int ny = 100;
Eigen::Matrix<double, nx, ny> eXX;
eXX.setZero();
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
eXX(i, j) = i * 2 * EIGEN_PI / nx;
}
}
}
Also note that your code has undefined behavior because the j loop goes to <= ny due to the +1 in the loop condition, meaning that the last iterations cause out-of-bound accesses to the array. Indeed, Eigen issues an assertion (in debug).
Moreover, since Eigen matrices are column major by default, it is more efficient to exchange the row and column loops (but of course this only matters for larger matrices):
#include <Eigen/Core>
int main()
{
static const int nx = 10;
static const int ny = 100;
Eigen::Matrix<double, nx, ny> eXX;
eXX.setZero();
for (int j = 0; j < ny; j++) {
for (int i = 0; i < nx; i++) {
eXX(i, j) = i * 2 * EIGEN_PI / nx;
}
}
}
Since the elements of each row have the same value here, we can also use row() together with setConstant() to simplify the code:
#include <Eigen/Core>
int main()
{
static const int nx = 10;
static const int ny = 100;
Eigen::Matrix<double, nx, ny> eXX;
for (int i = 0; i < nx; i++) {
eXX.row(i).setConstant(i * 2 * EIGEN_PI / nx);
}
}
|
72,606,522 | 72,606,588 | Inserting values to 2D array using pointers | I successfully entered values to a 2D array without pointers
int main(){
int A[2][3];
for (int i=0; i<2; i++){
for(int j=0; j<3; j++){
A[i][j] = 2*i+3*j;
cout<<" "<<A[i][j]<<" ";
}
cout<<endl;
}
}
And the output is
0 3 6
2 5 8
Then I tried to reach the same outcome with pointers
int main(){
int A[2][3];
int (*p)[3] = A;
for (int i=0; i<2; i++){
for(int j=0; j<3; j++){
*(*A+j)= 2*i+3*j;
cout<<" "<<*(A[i]+j)<<" ";
}
cout<<endl;
}
}
And the output is
0 3 6
32758 1 0
any idea why I got a different result for the second array?
| This left operand of the assignment expression
*(*A+j)= 2*i+3*j;
does not depend on the index i. In fact it is equivalent to A[0][j]
Thus elements A[1][j] stay uninitialized.
Instead write
for (int i=0; i<2; i++){
for(int j=0; j<3; j++){
*( *( A + i) + j )= 2*i+3*j;
cout<<" "<<*(A[i]+j)<<" ";
}
cout<<endl;
}
Or with using the declared pointer p the program can look the following way
#include <iostream>
int main()
{
int A[2][3];
int (*p)[3] = A;
for ( int i=0; i < 2; i++ )
{
for ( int j=0; j<3; j++ )
{
*( *( p + i ) + j ) = 2*i+3*j;
std::cout << " " << *(A[i]+j) << " ";
}
std::cout << std::endl;
}
}
That is the expression *( p + i ) is the same as p[i] and the expression *( *( p + i ) + j ) is the same as p[i][j].
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.