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 |
|---|---|---|---|---|
71,826,510 | 71,826,651 | Print like a dataframe vector pairs c++ | I have a map:
std::map<string , double> params{{a , 1}, {b, 6 }, {c, 7}{d,8} }
I want to print it like a python dataframe:
a b c d
1 6 7 8
Also, I dont want it to run twice.
void join_parameters(std::pair<string , double> param){
std::map<string , double> params;
params.insert(param);
for(const auto& elem : params)
{
double a, b , c,d;
if (elem.first =="a"){
a = elem.second; }
else if (elem.first =="b"){
b = elem.second;}
else if (elem.first =="c"){
c = elem.second; }
else {
d = elem.second;
}
}
std::cout << "d " << "a "<< "b " << "c "<< "\n" << d << a << b << c <<std::endl ;
}
Do you have any suggestion for me?
| Your code only works for a map with 4 elements and it assumes that those elements have keys "a" till "d". If that is the case then I would suggest you to use a different data structure, for example
struct params_t {
double a,b,c,d;
};
If you do need the map then you should not make assumptions about number of elements or their keys.
You can use two strings to accumulate the two lines of output in a single loop:
#include <map>
#include <string>
#include <utility>
#include <iostream>
int main() {
std::map<std::string , int> params{{"a" , 1}, {"b", 6 }, {"c", 7},{"d",8} };
std::pair<std::string,std::string> lines;
for (const auto& e : params) {
lines.first += e.first + " ";
lines.second += std::to_string(e.second) + " ";
}
std::cout << lines.first << '\n';
std::cout << lines.second << '\n';
}
Note that I changed the mapped type to int because it looks like you want to store integers. For double you need to adjust the code to get propper formatting.
|
71,826,513 | 71,826,650 | `std::remove` in template function causing problems with `vector.begin()` being `const` | The error message:
"binary '==': no operator found which takes a left-hand operand of type 'const _Ty' (or there is no acceptable conversion)"
The error seems to be because I'm giving std::remove a const value for the first argument, but I don't see exactly how v.begin() being unmodifiable would cause problems, nor why this error only occurs if the type of the vector is templated, as opposed to a known type vector.
The template function:
// Erases a every element of a certain value from a vector
template <typename T>
std::vector<T> eraseElement(std::vector<T> v, T elem)
{
typename std::vector<T>::iterator newEnd = std::remove(v.begin(), v.end(), elem);
v.erase(newEnd, v.end());
return v;
}
An example of the way I'm calling the template function:
struct exampleStruct
{
int x;
}
std::vector<exampleStruct> v;
exampleStruct elem;
elem.x = 2451;
v.push_back(elem);
v = eraseElement(v, elem);
|
nor why this error only occurs if the type of the vector is templated, as opposed to a known type vector.
It also occurs if you substitute exampleStruct manually.
std::vector<exampleStruct> eraseElement(std::vector<exampleStruct> v, exampleStruct elem)
{
auto newEnd = std::remove(v.begin(), v.end(), elem);
v.erase(newEnd, v.end());
return v;
}
That's because there isn't an operator== for exampleStruct. You probably want something like
bool operator==(const exampleStruct & lhs, const exampleStruct & rhs)
{
return lhs.x == rhs.x;
}
or with a C++20 implementation
struct exampleStruct
{
int x;
friend bool operator==(const exampleStruct &, const exampleStruct &) = default;
};
|
71,826,978 | 71,833,066 | Why can't my programs find resource files when using bazel run //package | I apologise if the title is a bit vague - I didn't know how else to phrase it.
I am quite new to Bazel but one thing that I don't quite understand is why my program fails to find the resource files I specify using the data attribute for the cc_binary rule
For context I am trying to follow Lazy Foo's SDL2 tutorials and I have a directory structure somewhat like this
gltuts
|
+---lazy-foo-02
| |
| +---media
| |
| +---hello_world.bmp
|
+---lazy-foo-03
Here is what my BUILD file looks like inside of the lazy-foo-02 directory
cc_binary(
name = "lazy-foo-02",
srcs = [
"main.cpp",
],
data = glob(["media/*"]),
deps = [
"//subprojects:sdl2",
],
)
When I use the bazel run command (I use bazelisk)
bazelisk run //lazy-foo-02
I get an error saying my hello_world isn't found. I managed to find an executable in bazel-bin (well a symlink to the executable somewhere in the .cache/bazel/... directory structure.
Now the directory where the symlink is located has the media directory and when I execute from this symlink location, it works as expected.
Why would this not work using the bazel run command? Am I missing anything from the BUILD file?
I am happy to provide more information if needed.
Thanks
| Use the C++ runfiles library to find them. Add the dependency in your BUILD file:
cc_binary(
name = "lazy-foo-02",
srcs = [
"main.cpp",
],
data = glob(["media/*"]),
deps = [
"//subprojects:sdl2",
"@bazel_tools//tools/cpp/runfiles",
],
)
and then where your code needs to find the file:
#include <string>
#include <memory>
#include "tools/cpp/runfiles/runfiles.h"
using bazel::tools::cpp::runfiles::Runfiles;
int main(int argc, char** argv) {
std::string error;
std::unique_ptr<Runfiles> runfiles(
Runfiles::Create(argv[0], &error));
if (runfiles == nullptr) {
return 1 // error handling
}
std::string path =
runfiles->Rlocation("gltuts/lazy-foo-02/media/hello_world.bmp");
}
See the header file for API docs and some notes on how to handle child processes, accessing them without argv[0], etc. @bazel_tools is a special repository name which is automatically provided by bazel itself, so no need for any WORKSPACE changes.
|
71,827,407 | 71,827,627 | Populating matrix by comparing 2 bits from 2 bitsets? | How to parse/read 2 bits at once from a bitset and process it?
I want to create a matrix that compares if 2 values match and populate the matrix with a 0 or 1.
This is what I did. This is for comparing 1 bit from both bitsets.
void bit2mat(bitset<14> ba, bitset<14> bb)
{
// print the bitsets
cout << "a: " << ba << endl;
cout << "b: " << bb << endl;
// print the matrix
for (int i = 0; i < ba.size(); i++)
{
for (int j = 0; j < bb.size(); j++)
{
if (ba[i] == bb[j])
{
cout << "1 ";
}
else
{
cout << "0 ";
}
}
cout << endl;
}
cout << endl;
}
This gives out
a: 00011100101101
b: 00110000001110
0 1 1 1 0 0 0 0 0 0 1 1 0 0
1 0 0 0 1 1 1 1 1 1 0 0 1 1
0 1 1 1 0 0 0 0 0 0 1 1 0 0
0 1 1 1 0 0 0 0 0 0 1 1 0 0
1 0 0 0 1 1 1 1 1 1 0 0 1 1
0 1 1 1 0 0 0 0 0 0 1 1 0 0
1 0 0 0 1 1 1 1 1 1 0 0 1 1
1 0 0 0 1 1 1 1 1 1 0 0 1 1
0 1 1 1 0 0 0 0 0 0 1 1 0 0
0 1 1 1 0 0 0 0 0 0 1 1 0 0
0 1 1 1 0 0 0 0 0 0 1 1 0 0
1 0 0 0 1 1 1 1 1 1 0 0 1 1
1 0 0 0 1 1 1 1 1 1 0 0 1 1
1 0 0 0 1 1 1 1 1 1 0 0 1 1
How do I make it read 2bits as 1 row and column. I want to get a matrix like this...
a: 00011100101101
b: 00110000001110
00 01 11 00 10 11 01
00 1 0 0 1 0 0 0
11 0 0 1 0 0 0 0
00 1 0 0 1 0 0 0
00 1 0 0 1 0 0 0
00 1 0 0 1 0 0 0
11 0 0 1 0 0 1 0
10 0 0 0 0 1 0 0
I know it can be done with vectors and arrays, but I'm working with bitsets. How to do generate this matrix using bitset?
| Your loops process one element at a time from each bitset. If you want to process two at a time the loop should go in steps of 2:
for (int i = 0; i < ba.size(); i+=2)
Then the two elements to be considered in the iteration are ba[i] and ba[i+1]. Same for the bb loop.
Note that the if and printing in your code can be simplified to just std::cout << (ba[i] == bb[j]);. Comparing pairs of bits and adding the headers, this is how it could be done:
#include <bitset>
#include <iostream>
void bit2mat(std::bitset<14> ba, std::bitset<14> bb) {
// print the bitsets
std::cout << "a: " << ba << std::endl;
std::cout << "b: " << bb << std::endl;
// print the matrix
std::cout << " \t";
for (int i=0; i < bb.size(); i+=2) std::cout << bb[i] << bb[i+1] << " ";
std::cout << "\n";
for (int i = 0; i < ba.size(); i+=2)
{
std::cout << ba[i] << ba[i+1] << "\t";
for (int j = 0; j < bb.size(); j+=2)
{
std::cout << (ba[i] == bb[j] && ba[i+1] == bb[j+1]) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
int main() {
std::bitset<14> a{"00011100101101"};
std::bitset<14> b{"00110000001110"};
bit2mat(a,b);
}
|
71,827,452 | 71,828,188 | Make thread array in C++ | I want to make a program that makes use of all threads.
I get the cores by:
const auto processorCount = std::thread::hardware_concurrency();
Then I tried to do this:
std::thread threads[processorCount];
for (int i = 0; i < processorCount; i++)
{
threads[i] = std::thread(addArray);
}
Then it gave me this error.
g++ main.cpp -o build
In file included from /usr/include/c++/11/thread:43,
from main.cpp:1:
/usr/include/c++/11/bits/std_thread.h: In instantiation of ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = int* (&)(int*, int*); _Args = {}; <template-parameter-1-3> = void]’:
main.cpp:62:46: required from here
/usr/include/c++/11/bits/std_thread.h:130:72: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
130 | typename decay<_Args>::type...>::value,
| ^~~~~
/usr/include/c++/11/bits/std_thread.h:130:72: note: ‘std::integral_constant<bool, false>::value’ evaluates to false
/usr/include/c++/11/bits/std_thread.h: In instantiation of ‘struct std::thread::_Invoker<std::tuple<int* (*)(int*, int*)> >’:
/usr/include/c++/11/bits/std_thread.h:203:13: required from ‘struct std::thread::_State_impl<std::thread::_Invoker<std::tuple<int* (*)(int*, int*)> > >’
/usr/include/c++/11/bits/std_thread.h:143:29: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = int* (&)(int*, int*); _Args = {}; <template-parameter-1-3> = void]’
main.cpp:62:46: required from here
/usr/include/c++/11/bits/std_thread.h:252:11: error: no type named ‘type’ in ‘struct std::thread::_Invoker<std::tuple<int* (*)(int*, int*)> >::__result<std::tuple<int* (*)(int*, int*)> >’
252 | _M_invoke(_Index_tuple<_Ind...>)
| ^~~~~~~~~
/usr/include/c++/11/bits/std_thread.h:256:9: error: no type named ‘type’ in ‘struct std::thread::_Invoker<std::tuple<int* (*)(int*, int*)> >::__result<std::tuple<int* (*)(int*, int*)> >’
256 | operator()()
| ^~~~~~~~
make: *** [Makefile:2: array] Error 1
What do I do now? Is their a simpler way of doing this?
| First of all, like in the comments suggested, I would recommend you to use std::vector as well, for example something like, std::vector<std::thread>. Here is a small example of how it could look like:
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
void print(int i)
{
std::cout << i << std::endl;
}
int main()
{
std::vector<std::thread> Threads;
for(int i = 0; i<std::thread::hardware_concurrency(); i++)
{
Threads.push_back(std::thread(print, i));
}
for(auto& i : Threads)
{
i.join();
}
return 0;
}
I hope this is solves your problem.
|
71,827,551 | 71,827,641 | Inconsistent behaviour c++ classes in classes | Edit based on the comments and the answer:
class Array {
public:
int size;
int *elements;
explicit Array(int maxSize) : size(0), elements(new int[maxSize]) {}
Array(Array &old) : elements(static_cast<int *>(malloc(sizeof(int) * size))), size(old.size) {
memcpy(elements, old.elements, sizeof(int) * size);
}
Array(Array &&old) noexcept : size(old.size), elements(old.elements) {
old.elements = nullptr;
}
~Array() {
delete[] elements;
}
void add(int e) {
elements[size++] = e;
}
};
class Base {
public:
Array a;
explicit Base(Array &a) : a(std::move(a)) {}
};
int main() {
Array a(5);
a.add(1);
std::cout << "Address: "<< a.elements << std::endl;
std::cout << "First element: "<< a.elements[0] << std::endl;
Array b = std::move(a);
std::cout << "Address: "<< b.elements << std::endl;
std::cout << "First element: "<< b.elements[0] << std::endl;
Base c(b);
std::cout << "Address: "<< c.a.elements << std::endl;
std::cout << "First element: "<< c.a.elements[0] << std::endl;
Base *d = static_cast<Base *>(malloc(sizeof(Base) * 2));
Array e = std::move(c.a);
std::cout << "Address: "<< e.elements << std::endl;
std::cout << "First element: "<< e.elements[0] << std::endl;
new (d) Base(e);
std::cout << "Address: "<< d[0].a.elements << std::endl;
std::cout << "First element: "<< d[0].a.elements[0] << std::endl;
}
I am trying to make some tailored structs and classes in c++, and I am having some issues in copy constructors of classes.
What I am trying to do is to create a class in which a pointer is copied within the copy constructor and replaced with nullpointer in the previous object. Everything is fine until I try to do it inside another class.
In that case the first element of the array change value for no reason (I can explain).
Here is a mre:
class Array {
public:
int *elements;
int size;
explicit Array(int maxSize) : size(0), elements(static_cast<int *>(malloc(sizeof(int) * maxSize))) {}
Array(Array &old) : size(old.size), elements(old.elements) {
old.elements = nullptr;
}
~Array() {
delete elements;
}
void add(int e) {
elements[size++] = e;
}
};
class Base {
public:
Array a;
explicit Base(Array &a) : a(a) {}
};
int main() {
Array a(5);
a.add(1);
std::cout << "Address: "<< a.elements << std::endl;
std::cout << "First element: "<< a.elements[0] << std::endl;
Array b = a;
std::cout << std::endl << "Old address: "<< a.elements << std::endl;
std::cout << "Address: "<< b.elements << std::endl;
std::cout << "First element: "<< b.elements[0] << std::endl;
Base c(b);
std::cout << std::endl << "Old address: "<< b.elements << std::endl;
std::cout << "Address: "<< c.a.elements << std::endl;
std::cout << "First element: "<< c.a.elements[0] << std::endl;
Base *d = static_cast<Base *>(malloc(sizeof(Base) * 2));
Array e = c.a;
std::cout << std::endl << "Old address: "<< c.a.elements << std::endl;
std::cout << "Address: "<< e.elements << std::endl;
std::cout << "First element: "<< e.elements[0] << std::endl;
d[0] = Base(e);
std::cout << std::endl << "Old address: "<< c.a.elements << std::endl;
std::cout << "Address: "<< d[0].a.elements << std::endl;
std::cout << "First element: "<< d[0].a.elements[0] << std::endl;
}
Output:
Address: 0x560838558eb0
First element: 1
Old address: 0
Address: 0x560838558eb0
First element: 1
Old address: 0
Address: 0x560838558eb0
First element: 1
Old address: 0
Address: 0x560838558eb0
First element: 1
Old address: 0
Address: 0x560838558eb0
First element: 1619232088
Process finished with exit code 0
| Your d object does not hold a valid array of Base objects. You merely allocated memory that may or may not be sufficient. But you never instantiated an object of type Base. So you cannot expect to use it.
If you need an old style array, just create it:
Base d[2] = {/*initialisation*/};
or use new if you need it on the free store. Usually, if you use malloc or its counterpart free in C++, you are likely doing something wrong.
Also, and not directly related, have a look at std::exchange.
|
71,828,288 | 71,828,512 | Why is std::aligned_storage to be deprecated in C++23 and what to use instead? | I just saw that C++23 plans to deprecate both std::aligned_storage and std::aligned_storage_t as well as std::aligned_union and std::aligned_union_t.
Placement new'd objects in aligned storage are not particularly constexpr friendly as far as I understand, but that doesn't appear to be a good reason to throw out the type completely. This leads me to assume that there is some other fundamental problem with using std::aligned_storage and friends that I am not aware of. What would that be?
And is there a proposed alternative to these types?
| Here are three excerpts from P1413R3:
Background
aligned_* are harmful to codebases and should not be used. At a high level:
Using aligned_* invokes undefined behavior (The types cannot provide storage.)
The guarantees are incorrect (The standard only requires that the type be at least as large as requested but does not put an upper bound on the size.)
The API is wrong for a plethora of reasons (See "On the API".)
Because the API is wrong, almost all usage involves the same repeated pre-work (See "Existing usage".)
On the API
std::aligned_* suffer from many poor API design decisions. Some of these are shared, and some are specific to each. As for what is shared, there are three main problems [only one is included here for brevity]:
Using reinterpret_cast is required to access the value
There is no .data() or even .data on std::aligned_* instances.
Instead, the API requires you to take the address of the object, call reinterpret_cast<T*>(...) with it, and then
finally indirect the resulting pointer giving you a T&. Not only does this mean that it cannot be used in constexpr, but
at runtime it's much easier to accidentally invoke undefined behavior. reinterpret_cast being a requirement for use
of an API is unacceptable.
Suggested replacement
The easiest replacement for aligned_* is actually not a library feature. Instead, users should use a properly-aligned
array of std::byte, potentially with a call to std::max(std::initializer_list<T>) . These can be found in the
<cstddef> and <algorithm> headers, respectively (with examples at the end of this section).
Unfortunately, this replacement is not ideal. To access the value of aligned_*, users must call reinterpret_cast on
the address to read the bytes as T instances. Using a byte array as a replacement does not avoid this problem. That said, it's important to recognize that continuing to use reinterpret_cast where it already exists is not nearly as bad as newly introducing it where it was previously not present. ...
The above section from the accepted proposal to retire aligned_* is then followed with a number of examples, like these two replacement suggestions:
// To replace std::aligned_storage
template <typename T>
class MyContainer {
private:
//std::aligned_storage_t<sizeof(T), alignof(T)> t_buff;
alignas(T) std::byte t_buff[sizeof(T)];
};
// To replace std::aligned_union
template <typename... Ts>
class MyContainer {
private:
//std::aligned_union_t<0, Ts...> t_buff;
alignas(Ts...) std::byte t_buff[std::max({sizeof(Ts)...})];
};
|
71,828,383 | 71,828,936 | C++ If statement before case in switch | I am tasked to rewrite some old software for my company and found an interesting construct inside the sources.
switch(X){
if(Y==Z){
case A: ... break;
case B: ... break;
}
case C: ... break;
default: ...;
}
The compiler warns me, that the code inside the if statment will not be executed but while testing it just seems that the if statment is not validated, the case statments however are.
Is there any reason, maybe early C++ days as some of the code is over 20 years by now, why you would write a construct like that? It is in production code so it does seem to do something?
I would be thankfull for any inside why this might have been done and if I can just ignore it as the compiler seems to do.
Edit:
It is also occuring multiple times, so it does not seem to be a simple error. This is what is confusing me.
Edit2:
Here is the example I used for testing. I am not sure how helpful it is however the origial code is inside a 1200 line monster function so creating one from that is basically impossible.
for (int i=0; i<5;i++)
{
switch(i)
{
if (i==0 || i ==1)
{
cout << "reached before case";
case 0: cout << "inside case 0" << std::endl; break;
case 1: cout << "inside case 1" << std::endl; break;
case 2: cout << "inside case 2" << std::endl; break;
}
case 3: cout << "inside case 3" << std::endl; break;
default: cout << "inside default" << std::endl;
}
}
|
Is there any reason ... why you would write a construct like that?
Only the author knows for sure (even they might not know). If there is source versioning metadata available, then associated commit message might be useful. Without more information, we can only guess what they were thinking. Some potential answers:
The author assumed that the condition of the if-statement would have some effect, but they were wrong and the mistake wasn't tested.
It's a vestigial result of some refactoring.
Perhaps some code was removed that used to make the statement meaningful.
Or perhaps it was copied from elsewhere where it did have a meaning.
Or perhaps there used to be a series of if-statements and there was an intention to replace them with a switch, but the change was half-assed.
|
71,828,716 | 71,829,912 | msys2 g++ - Entry Point Not Found | I installed msys2 and gcc according to this tutorial. However, when I am using the g++.exe in C:\msys64\mingw64\bin\ , I could not run the following program after compilation:
#include <deque>
int main() {
std::deque<int> d;
d.push_back(1);
return 0;
}
with an error of The procedure entry point _ZSt28__throw_bad_array_now_lengthv could not be located in the dynamic link library. However the following program worked fine:
#include <iostream>
int main() {
std::cout << "hi" << std::endl;
return 0;
}
I also tried using the g++.exe inside C:\msys64\usr\bin, in which case I got an error of
0 [main] cc1plus (8892) C:\msys64\usr\lib\gcc\x86_64-pc-msys\11.2.0\cc1plus.exe: *** fatal error - cygheap base mismatch detected - 0x180349408/0x180347408. This problem is probably due to using incompatible versions of the cygwin DLL. Search for cygwin1.dll using the Windows Start->Find/Search facility and delete all but the most recent version. The most recent version *should* reside in x:\cygwin\bin, where 'x' is the drive on which you have installed the cygwin distribution. Rebooting is also suggested if you are unable to find another cygwin DLL.
which seems really strange. I restarted my computer once and the problem persists. Any help is appreciated in advance.
| The problem is a dll conflict with the cygwin1.dll dll. You likely have a dll with the same name as one required by your application in one of the folders of your OS PATH environment variable that is a different version of the required dll or less likely a different dll with the same name.
The conflict could also be in one of the other folders that your OS searches. This MSDN article describes how the Windows OS locates required dlls: https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order#search-order-for-desktop-applications
|
71,829,138 | 71,829,247 | Is it an ODR violation to have an inline templated function have different behavior due to if constexpr? | It's possible to detect if a type is complete https://devblogs.microsoft.com/oldnewthing/20190710-00/?p=102678
I have reason to want to provide a different (inlinable) implementation if a type is complete.
Is it an ORD violation for a templated function to behave differently in different translation units based on an if constexpr in the function? In a sense, it's the "same" function in the different translation units (it's not macros creating different definitions at a C++ source level, which is an ODR violation).
Here's a simple example:
#include <iostream>
#include <type_traits>
// From https://devblogs.microsoft.com/oldnewthing/20190710-00/?p=102678
template<typename, typename = void>
constexpr bool is_type_complete_v = false;
template<typename T>
constexpr bool is_type_complete_v
<T, std::void_t<decltype(sizeof(T))>> = true;
template <typename T>
T* loggingGetRef(T* x) {
if constexpr (is_type_complete_v<T>) {
std::cout << "Complete!" << std::endl;
} else {
std::cout << "Incomplete!" << std::endl;
}
return x;
}
struct S
//{} // <- Uncomment this to make loggingGetRef be "different" through if constexpr.
;
int main() {
S* ptr = nullptr;
loggingGetRef(ptr);
}
https://godbolt.org/z/q1soa58PY
For my application, I would want the two if constexpr branches to outwardly act the same (unlike this example that prints different things) so from a correctness standpoint, it would be OK if the linker picked the assembly for either implementation and used that everywhere. It's just that in a translation unit where T is complete we may be able to get better performance (and I fully expect it to be inlined).
| ODR is not based on "templated functions"; it is based on actual functions. Templates generate functions based on template parameters. Each unique set of template parameters represents a different function. Different functions generated from the same template are different functions. There are no ODR expectations between different functions, regardless of what created them.
loggingGetRef<S> is the name of a particular function. If you do something that causes loggingGetRef<S> to generate differently due to constant expressions, you have ill-formed code (no diagnostic required). But that isn't a matter of ODR violations; that's a violation of the rules of template instantiation. A template that is instantiated with a specific set of parameters must be the same in all translation units that instantiate it with those parameters. Period.
|
71,829,150 | 71,830,225 | Build tools broken after uninstalling Xcode | When I use make to build my C++ project from the command line (cmake .., make) after installing and uninstalling xcode, make outputs make[2]: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++: No such file or directory
xcode-select -p output:
/Library/Developer/CommandLineTools
sudo xcode-select --install output:
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
xcode-select --reset output: nothing
I uninstalled and reinstalled the xcode command line tools and it still gives the same No such file or directory error
| CMake stores the results of its system introspection - the full path to the compiler used is one of them - in a file called CMakeCache.txt.
If you change something in your system that invalidates these results you need to clear the cache, i.e. delete the CMakeCache.txt file in the build folder.
|
71,829,191 | 71,831,011 | The formal parameter in the function is a structure pointer. There will be no error in how to write the argument | This is a code I wrote today. The problem is as follows:
The school is doing the project. Each teacher leads 5 students, a total of 3 teachers. The demand is as follows.
Design the structure of students and teachers. In the structure of teachers, there are teachers' names and an array of 5 students as members
Students' members have names and test scores. Create an array to store 3 teachers, and assign values to each teacher and students through functions
Finally, print out the teacher data and the student data brought by the teacher., When I replace value delivery with address delivery, the error code is as follows:
#include<iostream>;
using namespace std;
#include<string>;
#include<ctime>;
struct Student {
string name;
int score;
};
struct Teacher {
string name;
struct Student sArray[5];
};
void printTeacher(struct Teacher tArray[], int len) {
for (int i = 0; i < len; i++) {
cout << "老师的姓名为" << tArray[i].name << endl;
for (int j = 0; j < 5; j++) {
cout << "\t学生的姓名为:" << tArray[i].sArray[j].name << " 学生的成绩为:" << tArray[i].sArray[j].score << endl;
}
}
}
void allocateSpace(struct Teacher * tArray[], int * len) {
string nameseed = "ABCDE";
string tname = "教师";
string sname = "教师";
for (int i = 0; i < * len; i++) {
tArray[i] -> name = tname + nameseed[i];
for (int j = 0; j < 5; j++) {
tArray[i] -> sArray[j].name = sname + nameseed[j];
tArray[i] -> sArray[j].score = rand() % 61 + 40;
}
}
}
int main() {
srand((unsigned int) time(NULL)); //随机数种子 头文件 #include <ctime>
struct Teacher tArray[3];
int len = sizeof(tArray) / sizeof(tArray[0]);
cout << tArray << endl;
allocateSpace(tArray, & len);
printTeacher(tArray, len);
system("pause");
return 0;
}
allocateSpace(tArray, &len); Here I am prompted that arguments and formal parameters are incompatible.
Why and how?
| The problem is that &tArray is a pointer to an array of 3 Teacher elements,
i.e. a Teacher (*)[3] while your parameter is of type Teacher**. You may
try this:
void allocateSpace(struct Teacher* tArray, int len) {
// ^ no need for len to be a pointer
string nameseed = "ABCDE";
string tname = "??";
string sname = "??";
for (int i = 0; i < len; i++) {
tArray[i]. name = tname + nameseed[i];
for (int j = 0; j < 5; j++) {
tArray[i]. sArray[j].name = sname + nameseed[j];
tArray[i]. sArray[j].score = rand() % 61 + 40;
}
}
}
// ...
// Here, tArray automatically decays to a pointer to its first
// element, i.e. to &tArray[0]:
allocateSpace(tArray, len);
|
71,829,344 | 71,829,495 | Can we write a function which returns a function pointer to a function template? | Is it possible to write a function or method which can return a pointer to a template function or template method?
Example:
#include <iostream>
struct X1 {
static void Do(auto n) { std::cout << "1" << n << std::endl; }
// static auto GetPtr() { return X1::Do; } // how to write such a function?
};
struct X2 {
static void Do(int n) { std::cout << "2" << n << std::endl; }
//static auto GetPtr(){ return &Do; }
};
template <typename T> T magic(bool b, T t1, T t2) { return b ? t1 : t2; }
int main() {
auto l1 = magic(true, X1::Do, X2::Do);
// should be replaced by:
// auto l1 = magic( true, X1::GetPtr(), X2::GetPtr() );
l1(100);
}
If I compile the above out-commented functions, I got from gcc:
main.cpp:1845:39: error: unable to deduce 'auto' from 'X1::Do'
Background: I am currently trying to understand the overload resolution in same cases. In the given case you see that the overload for int is taken because one function pointer only has an int parameter so the second pointer overload can be found.
I was triggered by that question: Ternary operator applied to different lambdas produces inconsistent results
Here in an answer was suggested, that a lambda should be able to provide a conversion operator to a function pointer... and I did not see it :-)
| No you cannot return a pointer to a function template, because a function template is not a function. It is a template.
// static auto GetPtr() { return X1::Do; } // how to write such a function?
You need & to get a pointer to a member function, though Do is not a member function it is a member function template. You could return a pointer to X1::Do<int> or to X1::Do<double> but there is no pointer to X1::Do.
You can however return a functor with an overloaded call operator and that operator can be a template:
struct foo {
template <typename T>
void operator()(const T& t) {}
void operator()(int x){}
};
foo magic() { return foo{}; }
int main() {
magic()(3); // calls operator()(int)
magic()("hello world"); // calls operator()<const char[12]>
}
After rereading your question and the Q&A you link, I think you are maybe looking for this:
#include <iostream>
struct X1 {
static void Do(auto n) { std::cout << "1" << n << std::endl; }
static auto GetPtr() { return &X1::Do<int>; }
};
struct X2 {
static void Do(int n) { std::cout << "2" << n << std::endl; }
static auto GetPtr(){ return &Do; }
};
template <typename T> T magic(bool b, T t1, T t2) { return b ? t1 : t2; }
int main() {
auto l1 = magic( true, X1::GetPtr(), X2::GetPtr() );
l1(100);
}
As stated above, you cannot get a member function pointer to X1::Do but you can get a pointer to X1::Do<int>.
And as you are refering to conversion of lambdas to function pointers: Also lambdas with auto argument can only be converted to function pointers after choosing the argument type. Consider the example from cppreference:
void f1(int (*)(int)) {}
void f2(char (*)(int)) {}
void h(int (*)(int)) {} // #1
void h(char (*)(int)) {} // #2
auto glambda = [](auto a) { return a; };
f1(glambda); // OK
f2(glambda); // error: not convertible
h(glambda); // OK: calls #1 since #2 is not convertible
int& (*fpi)(int*) = [](auto* a) -> auto& { return *a; }; // OK
It is not possible to get a pointer to function of type auto(auto) (it isn't a type of a function to begin with). In all the calls above, after the conversion there is no auto anymore. Instead the requested type is deduced and a conversion to the respective function pointer is done.
|
71,829,506 | 71,838,847 | How to truncate a string wrapped in a bounding rect in Qt? | I have a simple QGraphicsView with text written over it. That text is wrapped under a bounding rect. I want to truncate the leading characters of text according to width of the bounding rect.
If my string is "I am loving Qt" and if my bounding rect is allowing 7 chars then it should show like ...g Qt. Text should not be written in multiple lines. According to width, more chars can be fit.
Along with I am interested to know, how the text can be aligned ?
widget.cpp
Widget::Widget(QWidget *parent)
: QGraphicsView(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
scene = new QGraphicsScene(this);
view = new QGraphicsView(this);
view->setScene(scene);
}
void Widget::on_textButton_clicked()
{
Text* t = new Text() ;
QString s = "I am loving Qt";
QGraphicsTextItem* text = t->drawText(s);
scene->addItem(text);
}
Text.h
class Text : public QGraphicsTextItem
{
public:
explicit Text(const QString &text);
Text();
QGraphicsTextItem* drawText(QString s);
virtual void paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
}
Text.cpp
QGraphicsTextItem* Text::drawText(QString s)
{
QGraphicsTextItem *t = new Text(s);
t->setTextWidth(8);
return t;
}
void Text::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->setPen(Qt::black);
painter->setBrush(QColor(230,230,230));
painter->drawRect(option->rect);
QGraphicsTextItem::paint(painter, option, widget);
}
| You may want to use QFontMetrics::elidedText by giving the font, width of your Text object and the actual text, and it will return the elided text. There are also a few Qt::TextElideMode options to choose from.
|
71,829,984 | 71,831,574 | Iterator traits on pointer to volatile | This code
#include <iterator>
#include <type_traits>
static_assert(std::is_same_v<typename std::iterator_traits<volatile int *>::value_type, volatile int>);
compiles on latest GCC and clang, but fails on MSVC 2019, that seems to remove volatile qualifier. See here on godbolt.
The const is removed, due to the standard specialization of std::iterator_traits for const T* and T*, but I think volatile should be kept.
Who is right?
Edit: I'm compiling with C++17.
| Extending the link comment by @康桓瑋 to an answer:
This is LWG issue 2952. Before its resolution value_type would be volatile-qualified, but its resolution changes it to remove the volatile qualification.
The resolution is incorporated into C++20 and MSVC, GCC and Clang all seem to implement it as such. (Meaning that the static_assert in the question fails when the compiler is set to C++20 mode.)
With regards to whether the resolution should be applied as a defect report to previous revisions of the standard, you can read some discussion here: https://github.com/microsoft/STL/issues/2612.
It seems that Microsoft's standard library implementation as well as LLVM's libc++ apply the issue resolution also to previous standard revision modes, while GCC's libstdc++ doesn't. I could not find any bug report or similar discussing the latter's choice.
|
71,830,460 | 71,857,441 | DirectX11 with a multiple video adapter (GPU) PC | Usually the DirectX11 initialization starts from creating a DirectX11 device:
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT nNumDriverTypes = ARRAYSIZE(driverTypes);
// Feature levels supported
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_1
};
UINT nNumFeatureLevels = ARRAYSIZE(featureLevels);
D3D_FEATURE_LEVEL featureLevel;
// Create device
for (UINT n = 0; n < nNumDriverTypes; ++n)
{
hr = D3D11CreateDevice(nullptr,driverTypes[n],nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT,featureLevels,nNumFeatureLevels,
D3D11_SDK_VERSION,&m_pDevice,&featureLevel,&m_pDeviceContext);
Then you create a swap chain for your window:
IDXGIDevice* pDXGIDevice = nullptr;
HRESULT hr = m_pDevice->QueryInterface(__uuidof(IDXGIDevice),
reinterpret_cast<void**>(&pDXGIDevice));
if (SUCCEEDED(hr))
{
IDXGIAdapter* pDXGIAdapter = nullptr;
hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter),
reinterpret_cast<void**>(&pDXGIAdapter));
if (SUCCEEDED(hr))
{
IDXGIFactory2* pDXGIFactory = nullptr;
hr = pDXGIAdapter->GetParent(__uuidof(IDXGIFactory2),
reinterpret_cast<void**>(&pDXGIFactory));
if (SUCCEEDED(hr))
{
DXGI_SWAP_CHAIN_DESC1 desc = {};
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
desc.BufferCount = 2;
desc.Width = nWindowWidth;
desc.Height = nWindowHeight;
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
hr = pDXGIFactory->CreateSwapChainForHwnd(m_pDevice,hWnd,
&desc,nullptr,nullptr,&m_pSwapChain);
My PC has two video adapters connected to two monitors. Adapter1 is connected to Monitor1. Adapter2 is connected to Monitor2. I know i can enumerate DXGI adapters and use a specific adapter for D3D11CreateDevice to create a DirectX11 device but this does not help me because i do not know which monitor shows my window.
How can i find which monitor shows my window? Do I have to use that monitor video adapter or can I use any adapter?
What happens if a user moves the window from Monitor1 to Monitor2? Does another adapter start showing the window?
Overall, how does DirectX11 handle such an issue?
| If you want to create a device that matches the adapter, you need a few changes in the call to :
D3D11CreateDevice
The idea is to provide the Adapter parameter yourself, so the process is :
1/Create the DXGI Factory yourself, using CreateDXGIFactory
2/Enumerate adapters from this factory, for this you use factory->EnumAdapters
3/For each adapter, you can enumerate which monitor is attached to them, adapter->EnumOutputs
4/You can then get the monitor description using output->GetDesc
5/From that description you can access the screen bounds eg :
output_desc.DesktopCoordinates
Now you can use the bounds of your window and perform the comparison (largest area, contained...)
When you found the most suitable monitor, you can use it for the device create function, such as :
IDXGIAdapter* my_requested_adapter;
D3D11CreateDevice(my_requested_adapter, D3D_DRIVER_TYPE_UNKNOWN , nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT,featureLevels,nNumFeatureLevels,
D3D11_SDK_VERSION,&m_pDevice,&featureLevel,&m_pDeviceContext);
So the only 2 differences in the call are that you specify the requested adapter in the first argument of the function, and driver type becomes D3D_DRIVER_TYPE_UNKNOWN (this is the only valid argument if you provide a specific adapter, since the driver type is inferred from it).
Now what happens if user moves the window to the second monitor (which is connected to the other graphics card)?
Initially it will "magically work", since the Desktop Window Manager (DWM) will detect that the content from your window needs to be presented on the other graphics card.
The major issue is, this will have a large impact on performances (since DWM will need to "download" the swapchain content from adapter1, and upload it to adapter2 then present it there.
So while it works, it involves a GPU round trip (you will also notice the DWM process suddenly increasing CPU usage, in a potential drastic way depending on your system).
Please note that it can (will) also add increased latency (we had a couple setups with multiple windows attached to a different monitors, each of them attached to a different GPU using a single device, it worked but the content was massively out of sync (the monitor attached to the other card was lagging behind), so we had to make sure that we used 2 devices instead, one for each card).
So if you want to make sure to always use the most relevant adapter, you need to get windows bounds each frame, and if the window is on a different adapter, you need to create a new device using that adapter instead (of course, that involves recreating every resource that was created on the previous one).
The bounds check process is really fast so there is basically no performance impact of checking that (you can also optimize and skip that check if only one adapter is present).
Note:
There is also the function called : IDXGISwapChain::GetContainingOutput
Which should give you the display monitor that contains the most of the window.
From that you could be able to perform a GetParent to retrieve the adapter, and check if the adapter is the same as the one currently used by the device.
I never tried that solution but that could also work (the issue with it is that you already need a Swapchain, so at creation time this is not usable).
|
71,830,787 | 71,843,515 | Make building for x86_64 but glfw installed from homebrew is for arm64 (aarch64) | My project was building fine with make, until I imported stb, now I get this error
ld: warning: ignoring file /opt/homebrew/lib/libglfw.3.4.dylib, building for macOS-x86_64 but attempting to link with file built for macOS-arm64
Undefined symbols for architecture x86_64:
"_glfwCreateWindow", referenced from:
HelloTriangleApplication::initWindow() in main.cpp.o
"_glfwCreateWindowSurface", referenced from:
HelloTriangleApplication::createSurface() in main.cpp.o
"_glfwDestroyWindow", referenced from:
HelloTriangleApplication::cleanup() in main.cpp.o
"_glfwGetFramebufferSize", referenced from:
HelloTriangleApplication::chooseSwapExtent(VkSurfaceCapabilitiesKHR const&) in main.cpp.o
HelloTriangleApplication::recreateSwapChain() in main.cpp.o
"_glfwGetRequiredInstanceExtensions", referenced from:
HelloTriangleApplication::getRequiredExtensions() in main.cpp.o
"_glfwGetWindowUserPointer", referenced from:
HelloTriangleApplication::framebufferResizeCallback(GLFWwindow*, int, int) in main.cpp.o
"_glfwInit", referenced from:
HelloTriangleApplication::initWindow() in main.cpp.o
"_glfwPollEvents", referenced from:
HelloTriangleApplication::mainLoop() in main.cpp.o
"_glfwSetFramebufferSizeCallback", referenced from:
HelloTriangleApplication::initWindow() in main.cpp.o
"_glfwSetWindowUserPointer", referenced from:
HelloTriangleApplication::initWindow() in main.cpp.o
"_glfwTerminate", referenced from:
HelloTriangleApplication::cleanup() in main.cpp.o
"_glfwWaitEvents", referenced from:
HelloTriangleApplication::recreateSwapChain() in main.cpp.o
"_glfwWindowHint", referenced from:
HelloTriangleApplication::initWindow() in main.cpp.o
"_glfwWindowShouldClose", referenced from:
HelloTriangleApplication::mainLoop() in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [vulkanLearning] Error 1
make[1]: *** [CMakeFiles/vulkanLearning.dir/all] Error 2
make: *** [all] Error 2
It seems like the program is compiling for x86_64, but the libglfw I've installed from homebrew is for aarch64. How do I get it to compile for aarch64?
CMakelists.txt is using C++20, it's a Vulkan proj (Using custom env vars)
cmake_minimum_required (VERSION 3.12)
project(
vulkanLearning VERSION 0.1.0
DESCRIPTION "vulkanLearning"
LANGUAGES CXX
)
# Specify the C++ standard
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_EXTENSIONS OFF)
# Set the default path for built executables to the "bin" directory
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build)
# Set the default path for built libraries to the "lib" directory
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
add_executable(${PROJECT_NAME} main.cpp)
find_package(Vulkan REQUIRED)
find_package(glfw3 3.3 REQUIRED)
if (VULKAN_FOUND)
message(STATUS "Found Vulkan, Including and Linking now")
include_directories(${Vulkan_INCLUDE_DIRS})
target_link_libraries (${PROJECT_NAME} ${Vulkan_LIBRARIES} glfw)
endif (VULKAN_FOUND)
| It seems as if CMake is building for x86_64 even though your processor runs on arm64. This is influenced by CMAKE_HOST_SYSTEM_PROCESSOR, so that should be arm64.
Setting the CMAKE_OSX_ARCHITECTURE should override that default so that it will build your application for arm64:
set(CMAKE_OSX_ARCHITECTURES "arm64")
That will force clang (or whatever compiler you're using) to compile for arm64.
|
71,831,583 | 71,832,363 | ignoring #pragma comment ws2_32.lib [-Wunknown-pragmas] | I am trying to compile some C++ code using Qt creator that has to connect to a socket for sending and receiving data. I have linked the library file, added the flag win32: LIBS+= -lWS2_32. Attaching the code snippet below:
...
#include<winsock2.h>
#pragma comment(lib,"Ws2_32.lib")
#include<windows.h>
...
WSADATA wsa;
SOCKET s;
uint8_t* encode_buffer;
uint8_t* decode_buffer;
uint16_t encode_buffer_length;
uint16_t decode_buffer_length;
if (send(s, encode_buffer, encode_buffer_length,0)<0){
...
}
if((recv_size=recv(s, decode_buffer, decode_buffer_length,0))== SOCKET_ERROR){
...
}
And my following issues are:
Warning: ignoring #pragma comment [-Wunknown-pragma]
Error: invalid conversion from 'uint8_t* {aka unsigned char*} to 'const char*'[-fpermissive]
Error: invalid conversion from 'uint8_t* {aka unsigned char*} to 'char*'[-fpermissive]
Error: no matching function for call to 'send'
Error: no matching function for call to 'recv'
Warning: unknown pragma ignored
I have added the ws2_32.lib file to the project as an external library, and mentioned it in the #pragma directive.
Not sure where I am going wrong.
Edit: Thanks! Reinterpret_cast solved the issue
| Regarding the warnings (not errors), the #pragma you are using is not supported by most compilers (Microsoft and Embarcadero compilers do). So just remove it altogether (you already link to the library in the project makefile), or at least disable it with an appropriate #if/def.
As for the rest of the errors, send() and recv()expect char* pointers, not uint8* pointers. A simple type-cast will suffice.
Try this:
...
#if defined(_MSC_VER) || defined(__BORLANDC__)
#pragma comment(lib,"Ws2_32.lib")
#endif
...
if (send(s, reinterpret_cast<char*>(encode buffer), encode_buffer_length, 0) < 0) {
...
}
if ((recv_size = recv(s, reinterpret_cast<char*>(decode buffer), decode_buffer_length, 0)) == SOCKET_ERROR) {
...
}
...
|
71,831,619 | 71,831,722 | How to format unix time (sec+usec+nsec) string? | I have this function which works just fine. It gives me current system time the way I need:
struct Timer
{
struct timespec ts;
char buff[16];
char res[64];
public:
char* GetTimestampNow()
{
timespec_get(&ts, TIME_UTC);
strftime(buff, sizeof buff, "%T", gmtime(&ts.tv_sec));
snprintf(res, 64, "%s.%09ld", buff, ts.tv_nsec);
return res;
}
char* GetTimestamp(int sec, int usec) {
// ??? how do I convert raw readings into timespec or anything else I can use in strftime?
strftime(buff, sizeof buff, "%T", gmtime(&ts.tv_sec));
snprintf(res, 64, "%s.%09ld", buff, ts.tv_nsec);
return res;
}
char* GetTimestamp(int sec, int usec, int nsec) {
// same question plus nanosecs
};
Now I need to also be able to print timestamps I receive from 3rd party lib in 2-3 variables - sec, usec, nsec (optional). Can I somehow construct timespec from these values and reuse the code I already have?
| You don't need a timespec structure.
Notice how all the gmtime calls only use the tv_sec field of the structure? You can use the sec argument directly in the gmtime call.
As for the nanoseconds, you could multiply usec with 1000 to get the corresponding nanoseconds.
So something like:
char buff[16]; // No need to make this a member variable, it can be local
strftime(buff, sizeof buff, "%T", gmtime(&sec));
snprintf(res, 64, "%s.%09ld", buff, usec * 1000);
In the third overload, just add nsec to the result of usec * 1000.
I would rather recommend you create a utility function for the creation of the string, which all the other functions are calling.
Like
class Timer
{
public:
std::string GetTimestampNow()
{
timespec ts;
timespec_get(&ts, TIME_UTC);
return GetTimestampHelper(ts.tv_sec, ts.tv_nsec);
}
std::string GetTimestamp(time_t sec, long usec)
{
return GetTimestampHelper(sec, usec * 1000);
}
std::string GetTimestamp(time_t sec, long usec, long nsec)
{
return GetTimestampHelper(sec, usec * 1000 + nsec);
}
private:
std::string GetTimestampHelper(time_t sec, long nsec)
{
char buff[64];
strftime(buff, sizeof buff, "%T", gmtime(&sec));
char res[64];
snprintf(res, sizeof res, "%s.%09ld", buff, nsec);
return res;
}
};
And unless there's code and requirements not mentioned, there's really no need for these member functions to be non-static.
And the Timer names implies something like stop-watch, so the class should probably be renamed as well.
|
71,831,717 | 71,832,909 | How to link a C++ program to the NTL library using Bazel | I would like to using Bazel to build a C++ project that links to some external libraries such as NTL. However, I can't find a way to make Bazel to build any program that includes NTL. Here is an example. Consider the following file structure:
/project-root
|__main
| |__BUILD
| |__example.cc
|
WORKSPACE
where WORKSPACE is just an empty file at the root of my project. The content of example.cc is:
#include <iostream>
int main()
{
int a = 5;
std::cout << "a = " << a << std::endl;
return 0;
}
The content of BUILD is:
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(
name = "example",
srcs = ["example.cc"],
)
I build the project as follows:
bazel build //main:example
and I obtain:
INFO: Analyzed target //main:example (38 packages loaded, 260 targets configured).
INFO: Found 1 target...
Target //main:example up-to-date:
bazel-bin/main/example
INFO: Elapsed time: 5.175s, Critical Path: 0.58s
INFO: 6 processes: 4 internal, 2 darwin-sandbox.
INFO: Build completed successfully, 6 total actions
I then run:
./bazel-bin/main/example
which returns:
a = 5
Everything works as expected. However, if I include the NTL library, I am unable to build the project. Consider the following update to example.cc
#include <iostream>
#include <NTL/ZZ.h>
int main()
{
int a = 5;
NTL::ZZ b = NTL::ZZ(13);
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
return 0;
}
If I wanted to compile example.cc directly, I would execute the following:
g++ main/example.cc -o main/example --std=c++11 -lntl
However, I would like to do it using Bazel (since I will have to build for different targets, I am going to test with Google Test, and some other reasons that made me want to try Bazel.)
According to this post, I would be able to do what I want by adding linkopts in my BUILD file:
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(
name = "example",
srcs = ["example.cc"],
linkopts = ["-lntl"],
)
However, when I try to build it, I get:
ERROR: /Users/.../bazel_example/main/BUILD:3:10: Compiling main/example.cc failed: (Aborted): wrapped_clang_pp failed: error executing command external/local_config_cc/wrapped_clang_pp '-D_FORTIFY_SOURCE=1' -fstack-protector -fcolor-diagnostics -Wall -Wthread-safety -Wself-assign -fno-omit-frame-pointer -O0 -DDEBUG '-std=c++11' ... (remaining 31 arguments skipped)
Use --sandbox_debug to see verbose messages from the sandbox
main/example.cc:3:10: fatal error: 'NTL/ZZ.h' file not found
#include <NTL/ZZ.h>
^~~~~~~~~~
1 error generated.
Error in child process '/usr/bin/xcrun'. 1
Target //main:example failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 3.833s, Critical Path: 0.39s
INFO: 5 processes: 5 internal.
FAILED: Build did NOT complete successfully
The same post I previously mentioned talks about an alternative by importing whatever library you need to the project. I've seen some people recommending including the path to the headers of the library directly in the project managed by Bazel.
I wonder if there is a way to successfully build the project with Bazel while just "flagging" the NTL library so I can use it in my project.
I am specifically referring to the NTL library but this would be my desired approach to any other external library available in the system.
| I got Bazel to build my project and link to NTL by following the steps in this answer. Refer to this link for the specifics. However, the referred solution was not enough for the particular case of the NTL library. The "problem" is that NTL uses GMP by default. When I saw the build failing because Bazel "didn't recognize" GMP I was a bit concerned. One library can have many dependencies and addressing each one of them just to get one library to work could be cumbersome.
Thankfully, the only extra required step was to apply for GMP the same configuration I applied for NTL.
I modified my BUILD file including the dependencies I need to compile my project:
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(
name = "example",
srcs = ["example.cc"],
deps = ["@ntl//:ntl_", "@gmp//:gmp_"],
)
Then I created the "dependencies" directory and put two files in there. One is BUILD.ntl with the following content:
cc_library(
name = "ntl_",
srcs = glob(["lib/*.dylib"] + ["lib/*.a"]),
hdrs = glob(["include/NTL/*.h"]),
strip_include_prefix = "include/",
visibility = ["//visibility:public"]
)
and BUILD.gmp
cc_library(
name = "gmp_",
srcs = glob(["lib/*.dylib"] + ["lib/*.a"]),
hdrs = glob(["include/*.h"]),
strip_include_prefix = "include/",
visibility = ["//visibility:public"]
)
Finally, I added to the previously empty WORKSPACE file the following:
new_local_repository(
name = "ntl",
path = "/usr/local/var/homebrew/linked/ntl",
build_file = "dependencies/BUILD.ntl",
)
new_local_repository(
name = "gmp",
path = "/usr/local/var/homebrew/linked/gmp",
build_file = "dependencies/BUILD.gmp",
)
Obviously, the path under new_local_repository can be platform/machine/user specific. I installed NTL and GMP using Homebrew those paths.
I wanted a solution that could be as "seamless" as possible. Without knowing any other "cleaner" approach, I will stick to this one.
Now I just need to cleanup the previous failed builds:
bazel clean
and build it again:
bazel build //main:example
so I obtain:
INFO: Analyzed target //main:example (40 packages loaded, 391 targets configured).
INFO: Found 1 target...
Target //main:example up-to-date:
bazel-bin/main/example
INFO: Elapsed time: 5.128s, Critical Path: 1.54s
INFO: 129 processes: 127 internal, 2 darwin-sandbox.
INFO: Build completed successfully, 129 total actions
When I run
./bazel-bin/main/example
I see the expected result:
a = 5
b = 13
|
71,832,233 | 71,832,390 | why does character_arrays.exe has stopped working error pop up? | my code is working fine. Its showing the right results in the file but after executing the code,an error message pops up saying "character_array.exe has stopped working". Can anyone tell why that error appears??
#include <iostream>
#include<cstring>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string name[20], roll_no[20];
int price[20], k=0;
ifstream data;
ofstream dout;
char fname[4];
char fname1[]={"dout"};
cout<<"enter file name : ";
cin.getline(fname, 20);
if(strcmp(fname,fname1) !=0)
{
cout<<"file names do not match";
}
else{
data.open("new.txt");
while(!data.eof())
{
for(int i=0; i<20; i++)
{
data>>name[i]>>roll_no[i]>>price[i];
k++;
}
}
data.close();
cout<<"data in the text file is:"<<endl;
for(int i=0; i<6; i++)
{
cout<<name[i]<<" "<<roll_no[i]<<" "<<price[i]<<endl;
}
dout.open("output.txt");
for(int i=0; i<6; i++)
{
dout<<name[i]<<" "<<roll_no[i]<<" "<<price[i]<<endl;
}
}
return 0;
}
| I am assuming that your issue is an infinite loop, if your IDE supports breakpoints, I would recommend adding one to your while loop and seeing if it runs forever.
|
71,832,605 | 71,834,154 | operator+= between custom complex type and std::complex | I want my custom complex type to be able to interact with std::complex, but in certain cases, the compiler do not convert my type to std::complex.
Here is a minimal working example:
#include <complex>
#include <iostream>
template <typename Expr>
class CpxScalarExpression
{
public:
inline std::complex< double > eval() const { return static_cast<Expr const&>(*this).eval(); }
inline operator std::complex< double >() const { return static_cast<Expr const&>(*this).eval(); }
};
class CpxScalar : public CpxScalarExpression<CpxScalar>
{
public:
CpxScalar() : m_value(0) {}
CpxScalar(const double value) : m_value(value) {}
CpxScalar(const double real_value, const double imag_value) : m_value(real_value, imag_value) {}
CpxScalar(const std::complex< double > value) : m_value(value) {}
template<typename Expr>
CpxScalar(const CpxScalarExpression< Expr >& expr) : m_value(expr.eval()) {}
public:
inline std::complex< double > eval() const { return m_value; }
private:
std::complex< double > m_value;
};
int main()
{
CpxScalar a(10,-5);
//std::complex< double >* b = reinterpret_cast< std::complex< double >* >(&a);
std::complex< double > b = a;
b += a;
//std::cout << b->real() << " " << b->imag();
std::cout << b.real() << " " << b.imag();
}
The compiler fails at deducing which operator+= to call and returns the following error
est.cpp:50:4: error: no match for ‘operator+=’ (operand types are ‘std::complex<double>’ and ‘CpxScalar’)
50 | b += a;
| ~~^~~~
In file included from test.cpp:1:
/usr/include/c++/9/complex:1287:7: note: candidate: ‘std::complex<double>& std::complex<double>::operator+=(double)’
1287 | operator+=(double __d)
| ^~~~~~~~
/usr/include/c++/9/complex:1287:25: note: no known conversion for argument 1 from ‘CpxScalar’ to ‘double’
1287 | operator+=(double __d)
| ~~~~~~~^~~
/usr/include/c++/9/complex:1329:9: note: candidate: ‘template<class _Tp> std::complex<double>& std::complex<double>::operator+=(const std::complex<_Tp>&)’
1329 | operator+=(const complex<_Tp>& __z)
| ^~~~~~~~
/usr/include/c++/9/complex:1329:9: note: template argument deduction/substitution failed:
test.cpp:50:7: note: ‘CpxScalar’ is not derived from ‘const std::complex<_Tp>’
50 | b += a;
| ^
Is there a way to overcome this issue ?
| Providing your own overload for the operator is the way to go.
However, there's a few things to keep in mind:
Since you already have a cast available, all you have to do is to use it and let the regular operator take it from there.
Since the type that is meant to "pose" as std::complex is CpxScalarExpression<Expr>, then that should be the one the overload operates on.
std::complex's operator+=() normally allows you to add together complex values of different types, so we should maintain that. Meaning the operator should be templated on the incoming std::complex's components type.
We need to make sure to return exactly whatever std::complex's operator+= wants to return. Using decltype(auto) as the return type of the overload provides you with just that.
Putting all of that together, we land at:
template<typename T, typename Expr>
constexpr decltype(auto) operator+=(
std::complex<T>& lhs,
const CpxScalarExpression<Expr>& rhs) {
return lhs += std::complex<double>(rhs);
}
Dropping that into the code you posted makes it work just as expected, and should give you feature parity with std::complex's operator+=().
|
71,832,753 | 71,876,171 | could not find "vswhere" | I'm trying to install boost to run PyGMO properly. However, after I unpack it in a directory (did not use git).
After running bootstrap vc142 (I'm using VScode V1.63.2 and I'm on windows). I'm getting this error:
Building Boost.Build engine
LOCALAPPDATA=C:\Users\wojci\AppData\Local
could not find "vswhere"
Call_If_Exists "..\bin\VCVARS32.BAT"
###
### Using 'msvc' toolset.
###
Followed by:
C:\Program Files\boost\boost_1_78_0\tools\build\src\engine>dir *.exe
Volume in drive C has no label.
C:\Program Files\boost\boost_1_78_0\tools\build\src\engine>copy /b .\b2.exe .\bjam.exe
The system cannot find the file specified.
Failed to build Boost.Build engine.
Does anyone know how to fix/work around this?
Thank you in advance
| I found the solution here (git)
Prerequisites:
First download and install MinGW installer mingw-w64-install.exe (I fot it from Sourceforge) and make sure you use x86_64 architecture.
Then download the boost file (boost_1_78_0.zip source)
Open and run cmd as admin
Enter the following command to link the MinFW folder in C:\
mklink /J C:\MinGW "C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64"
add MinGW to the system PATH:
set PATH=%PATH%;C:\MinGW\bin
setx /M PATH "%PATH%"
Check if you have at least g++ version of 8.1.0
g++ --version
Methodology to install boost:
Navigate to the install folder created and unzip and extract the boost_1_78_0.zip file into this folder
In the CMD navigated to the boost folder
cd C:\install\boost_1_78_0
Type the following to make directories for building and installing boost
mkdir C:\boost-build
mkdir C:\install\boost_1_78_0\boost-build
mkdir C:\boost
Setup boost.build (second line prepers b2, the third line builds boost.build with b2, and the fourth line adds C:\boost-build\bin to your session PATH variable)
cd C:\install\boost_1_78_0\tools\build
bootstrap.bat gcc
b2 --prefix="C:\boost-build" install
set PATH=%PATH%;C:\boost-build\bin
building boost (first line navigateds to boost directory, second line builds boost with b2 this can take a while)
cd C:\install\boost_1_78_0
b2 --build-dir="C:\install\boost_1_78_0\build" --build-type=complete --prefix="C:\boost" toolset=gcc install
Extra notes:
This should work for boost 1.68.0 too and might work for other version just replace 1_78_0 with 1_68_0.
At the end you should have three lines that look something like this:
...failed updating 72 targets...
...skipped 292 targets...
...updated 22164 targets...
It's totally fine if you have some failed and skipped files.
|
71,833,264 | 71,833,475 | C++ Weird behavior while giving a value to the the predecessor element of a matrix column (v[i][j-1]) | So I was trying to make a matrix where the elements of the main diagonal would increase by 3 one by one and I also wanted to change the values of the previous and the next element of the the main diagonal with their predecessor and succesor.
Something like this:
It all worked fine until the predecessor element. For some reason v[i][j-1] doesn't work?
I would like to mention I am a beginner.
Here is the code:
#include <iostream>
using namespace std;
int n, v[22][22];
int main()
{
cin >> n;
int k = 1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == j)
{
v[i][j] = k;
v[i][j + 1] = k + 1;
v[i][j - 1] = k - 1; //this is the part where it doesn't work
}
cout << v[i][j] << " ";
}
k += 3;
cout << "\n";
}
}
Here is the result I am getting
Edit: I also tried it when i and j start from 1, so there won't be any negative index value. It still doesn't work.
| For starters there is no need to use nested for loops. It is enough to use only one for loop.
When i is equal to 0 and j is equal to 0 then this expression v[i][j - 1] access memory outside the array that invokes undefined behavior.
The same problem exists when n is equal to 22 for the expression and i and j are equal to n - 1 for this v[i][j + 1] .
You should check these situations.
And this output
cout << v[i][j] << " ";
can occur for v[i][j-1] when it was not yet updated.
Also try to declare variables in minimum scope where they are used. For example there is no need to declare the array in the global namespace.
Here is shown how you can organize the loops.
int value = 1;
for (size_t i = 0; i < n; i++)
{
v[i][i] = value;
if (i != 0) v[i][i - 1] = value - 1;
if (i != n - 1) v[i][i + 1] = value + 1;
value += 3;
}
for (const auto &row : v)
{
for (const auto &item : row)
{
std::cout << std::setw( 3 ) << item << ' ';
}
std::cout << '\n';
}
For example if n is equal to 5 then the output will be
1 2 0 0 0
3 4 5 0 0
0 6 7 8 0
0 0 9 10 11
0 0 0 12 13
|
71,833,797 | 71,833,936 | Here is a C++ program where it is showing that my function is out of scope. Can someone please tell me the errors and how to fix them | Question
You have to create a class, named Student, representing the student's details, as mentioned above, and store the data of a student. Create setter and getter functions for each element; that is, the class should at least have following functions:
get_age, set_age
get_first_name, set_first_name
get_last_name, set_last_name
get_standard, set_standard
Also, you have to create another method to_string() which returns the string consisting of the above elements, separated by a comma(,). You can refer to stringstream for this.
code:
#include <iostream>
using namespace std;
class Student{
private:
int age;
string fname;
string lname;
int std;
public:
void set_age(int a){age=a;;}
void set_fname(string f){fname=f;} //fname= first name
void set_lname(string l){lname=l;} //lname= last name
void set_std(int s){std=s;}
void get_age(){
cout<<age<<endl;
}
void get_fname(){
cout<<fname<<endl;
}
void get_lname(){
cout<<lname<<endl;
}
void get_std(){
cout<<std<<endl;
}
void to_string(){
string fl=lname+", "+fname; //fl stand for first and last
cout<<fl;
}
};
int main() {
Student z;
int a,s;
string f,l;
cin>>a;
z.set_age(a);
cin>>f;
z.set_fname(f);
cin>>l;
z.set_lname(l);
cin>>s;
z.set_std(s);
get_age();
to_string();
get_std();
return 0;
}
output
Solution.cpp:52:11: error: ‘get_age’ was not declared in this scope
cout<<get_age();
^~~~~~~
Solution.cpp:52:11: note: suggested alternative: ‘getdate’
cout<<get_age();
^~~~~~~
getdate
Solution.cpp:53:15: error: no matching function for call to ‘to_string()’
to_string();
^
| You create one Student instance, z, and call misc. setter member functions on that instance. When you then call the functions to print some of the values you've set, you forgot to tell the compiler which instance you want to print the values for. Since you only have one instance, z, add that before the member functions:
z.get_age();
z.to_string();
z.get_std();
Improvement suggestion: Functions that does not return a value but that prints the value would be better named print-something rather than get-something.
|
71,834,217 | 71,834,264 | What does 'NVP' mean in the context of C++ / serialization? | The C++ serialization library cereal uses the acronym NVP several times in its documentation without mentioning what it means.
A quick web search brings up further hits related to boost serialization, and on first glance I couldn't spot a full spelling of the acronym either. It seems to be some kind of C++ serialization related slang.
What does it stand for?
| It means "Name Value Pair".
KVP (Key-Value Pair) is another common acronym for the same concept you may have run into. They are interchangeable.
It seems to be some kind of C++ serialization related slang.
Not really. It's an acronym specific to boost::serialization. As far as I can tell, cereal inherited it out of its explicit positioning as an alternative to that original library.
|
71,834,336 | 71,955,244 | How to correctly include and link a proprietary shared object library in C++ | I have a linux c++ sdk that i need to integrate as a dependency into a .NET 6.0 bigger project.
This sdk is only conditionally included for the linux version of the software, i do already have the windows version running with no problems.
This skd exposes only classes in very nested namespaces, and as far as i'm aware, [DllImport] does not support class methods.
I do already know how to create a wrapper and expose functions with extern "C" and passing the sdk instances as pointers to a .NET Core application running with no problem under linux systems
My problem is that i do have no idea on how to succesfully compile/include/link the existing .so files into a .dll or .so that i can then [DllImport]
The sdk has been sent to me with the following structure (take name-of-lib as the placeholder name. I'm not sure if i can expose the real company name so i won't just in case):
run/
|- x86/
| +- {same files as x64 but i don't target x86 arcs so it's useless}
+- x64/
|- install.sh {see #1}
|- libNameModuleA.so.1.2.3
|- libNameModuleB.so.3.2.1
|- libNameApi.so.7.8.9
+- {etc. etc.}
lib/
|- lib-name-api/
| |- doc/
| | +- somehtmlautogenerateddocs.html
| |- include/
| | +- NameApi.h
| +- source/ {optionally for the top level apis}
| +- {varius header .h files}
|- name-of-lib-module-A/
| +- {same as previus, repeat for every .so file}
+- {etc. etc.}
{#1} script that craetes links as libName.so => libName.so.1 => libName.so.1.2 => etc
All of those library header files reference each other like they were in the same folder, using an #include "subLibraryModule.h" even if this file would actually be in something like ../../subLibrary/include/subLibraryModule.h.
Also, in the skd there are only headers.
now, what would be the (either, i don't really know waht would be the best tool) cmake, make, g++, gcc command, configuration or procedure to be able to include the top-level header that references all of the other ones in the compilation without a file not found error from the compiler?
Say i need to compile a single file wrapper.cpp that includes only the top level headers and contains only extern "C" functions
I've tried doing this with vscode and intellisense actually resolves the headers correctly, but when i try to compile it everything bursts into a fire of file-not-founds
Am I missing something? Is there further information or files i missed?
Thanks in advance.
| So i figured it out.
makefile
The only problem here is that i did not know how to use a glob pattern to include stuff automatically (like -Ilib/*/include) but whatever.
CC := g++
SRC := wrapper.cpp
OBJ := wrapper.o
OUT := libWrapper.so
INCs := -Ilib/lib-name-api/include -Ilib/name-lib-module-A/include {etc. etc.}
LIB := -L/usr/local/lib/installedLibNameSos/ -lNameModuleA -lNameModuleB {etc. etc.}
all: $(OUT)
$(OUT): $(OBJ)
$(CC) $(OBJ) -shared -o $(OUT) $(LIB)
$(OBJ): $(SRC)
$(CC) -c $(SRC) -o $(OBJ) $(INCs) $(LIB)
wrapper.cpp
#include <stdio.h>
#include "NameApi.h"
// varius using namespace and other import stuff
extern "C" int test (){
return 42;
}
extern "C" string somethingReturningAString (){
// calls and stuff to the native library
return "Hi mom"
}
obviusly the .so needs to be copied where the executable is
csharpClass.cs
using System;
using System.Runtime.InteropServices;
// extension not needed.
// the library will be loaded along with the required .so's
// that have been linked from /usr/local/lib/installedLibNameSos/
[DllImport("libWrapper")]
extern static int test ();
[DllImport("libWrapper")]
extern static string somethingReturningAString ();
Console.WriteLine(test());
// 42
Console.WriteLine(somethingReturningAString());
// Hi mom
resources:
Link .so file to .cpp file via g++ compiling
Call C++ library in C#
https://en.wikipedia.org/wiki/Platform_Invocation_Services (p/Invoke examples)
https://learn.microsoft.com/en-us/dotnet/standard/native-interop/cross-platform
(note: the process works perfectly. But i've been using a library written and documented by a spastic monkey. So yeah i've literally learned the basics of g++, make and got crippling depression for nothing. lol)
|
71,834,378 | 71,834,478 | Output numbers in reverse (C++) w/ vectors | I'm stuck for the first time on a lab for this class. Please help!
The prompt is:
Write a program that reads a list of integers, and outputs those integers in reverse. The input begins with an integer indicating the number of integers that follow. For coding simplicity, follow each output integer by a comma, including the last one.
Ex: If the input is:
5 2 4 6 8 10
the output is:
10,8,6,4,2,
2 questions: (1) Why does the vector not take user input unless the const int is included? (2) Why does the code not work in general? It seems to properly output, but with an error, and does not include the end line?
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int MAX_ELEMENTS = 20;
vector<int> userInts(MAX_ELEMENTS);
unsigned int i;
int numInts;
cin >> numInts;
for (i = 0; i < numInts; ++i) {
cin >> userInts.at(i);
}
for (i = (numInts - 1); i >= 0; --i) {
cout << userInts.at(i) << ",";
}
cout << endl;
return 0;
}
| Firstly, you need to specify the size because you are not using the vector's push_back functionality. Since you are only using at, you must specify the size ahead of time. Now, there's a few ways to do this.
Example 1:
cin >> numInts;
vector<int> userInts(numInts); // set the size AFTER the user specifies it
for (i = 0; i < numInts; ++i) {
cin >> userInts.at(i);
}
Alternatively, using push_back you can do:
vector<int> userInts; // set the size AFTER the user specifies it
for (i = 0; i < numInts; ++i) {
int t;
cin >> t;
userInts.push_back(t);
}
As for looping backwards, i >= 0 will always be true for unsigned numbers. Instead, you can use iterators.
for ( auto itr = userInts.rbegin(); itr != userInts.rend(); ++itr ) {
cout << *itr;
}
If you need to use indexes for the reverse loop, you can do:
for ( i = numInts - 1; i != ~0; --i ) { // ~0 means "not 0", and is the maximum value, I believe this requires c++17 or 20 though
cout << userInts.at(i);
}
|
71,834,788 | 72,159,147 | Why does the use of `std::aligned_storage` allegedly cause UB due to it failing to "provide storage"? | Inspired by: Why is std::aligned_storage to be deprecated in C++23 and what to use instead?
The linked proposal P1413R3 (that deprecates std::aligned_storage) says that:
Using aligned_* invokes undefined behavior (The types cannot provide storage.)
This refers to [intro.object]/3:
If a complete object is created ([expr.new]) in storage associated with another object e of type “array of N unsigned char” or of type “array of N std::byte” ([cstddef.syn]), that array provides storage for the created object if: ...
The standard then goes on to use the term "provides storage" in a few definitions, but I don't see it saying anywhere that using a different type as storage for placement-new (that fails to "provide storage") causes UB.
So, the question is: What makes std::aligned_storage cause UB when used for placement-new?
| The paper appears to be wrong on this.
If std::aligned_storage_t failed to "provide storage", then most uses of it would indirectly cause UB (see below).
But whether std::aligned_storage_t can actually "provide storage" appears to be unspecified. A common implementation that uses a struct with alignas(Y) unsigned char arr[X]; member (seemingly) does "provide storage" according to [intro.object]/3, even if you pass the address of the whole structure into placement-new, rather than the array. Even though this specific implementation isn't mandated now, I believe mandating it would be a simple non-breaking change.
If std::aligned_storage_t actually didn't "provide storage", then most use cases would cause UB:
Placement-new into an object that fails to "provide storage" is legal by itself, but...
This ends the lifetime of the object that failed to "provide storage" (aligned_storage_t), and, recursively, all enclosing objects. The next time you access any of those, you get UB.
Even if aligned_storage_t is not nested within other objects (which is rare), you'd have to be careful when destroying it, since calling its destructor would also cause UB, since its lifetime has already ended.
[basic.life]/1.5
... The lifetime of an object o of type T ends when:
— the storage which the object occupies ... is reused by an object that is not nested within [the object]
intro.object/4
An object a is nested within another object b if:
—a is a subobject of b, or
— b provides storage for a, or
— there exists an object c where a is nested within c, and c is nested within b.
|
71,834,820 | 71,834,862 | `std::launder` not returning correct data for Clang and GCC but is for msvc | Why doesn't std::launder return the correct value (2) in CLANG and GCC when the object is in the stack v in the heap? Even using std::launder.
std::launder is required. See this which says launder
is needed when replacing an object const qualified at the top level. This is because
basic.life disallows replacing complete const objects without std::launder, only
sub-objects.
#include <memory>
#include <iostream>
int main()
{
struct X { int n; };
const X *p = new const X{1};
const X x{1};
std::construct_at(&x, X{2}); // on stack
const int c = std::launder(&x)->n;
std::construct_at(p, X{2}); // allocated with new
const int bc = std::launder(p)->n;
std::cout << c << " " << '\n';
std::cout << bc << " " << '\n';
}
See Compiler Explorer.
| std::construct_at(&x, X{2}); has undefined behavior.
It is not allowed to create a new object in storage that was previously occupied by a const complete object with automatic, static or thread storage duration. (see [basic.life]/10)
Other than that you are correct that std::launder is required in the second case for the reasons you explained: Because the object you created with new is const-qualified. If it weren't for that the old object would be transparently replaceable with the new one.
|
71,834,995 | 71,866,195 | CMake find specific package of multiple packages with different versions (NCurses) | I currently have a CMake file that finds and links a library (NCurses) to another library
...
set(CURSES_NEED_NCURSES TRUE)
find_package(Curses REQUIRED)
include_directories(${CURSES_INCLUDE_DIR})
add_library(myLibrary STATIC ${sources})
target_link_libraries(myLibrary ${CURSES_LIBRARIES})
target_compile_options(myLibrary PUBLIC -std=c++20 -Wall -Wconversion)
...
This works fine, however unfortunately it is pulling up a different version than I need (5.7 instead of 6.1)
#include <ncurses.h>
#include <iostream>
int main()
{
std::cout << "VERSION: " << NCURSES_VERSION;
}
outputs: VERSION: 5.7
I do have the desired package installed under: /usr/local/ncurses/6_1.
But the logs seem to say it is pulling it from a different location: Found Curses: /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX11.3.sdk/usr/lib/libncurses.tbd
How can I specify which of these I want to use?
| Okay I have figured this out, to anyone else who might come across this.
First I installed the latest version of ncurses (6.3) from here: https://invisible-island.net/ncurses/#downloads-h2
(I downloaded the gzipped tar)
I then went through and deleted all references in my usr/local i could find to ncurses.
I then extracted the tar, and entered the new directory.
I ran just plain ./configure inside the directory (with no flags).
After that finished, I ran make
Then I ran make install, after removing symlinks to stop collisions, make install was able to run properly.
Ensure that the CMake variable CURSES_NEED_NCURSES is set to TRUE before finding the package:
set(CURSES_NEED_NCURSES TRUE)
find_package(Curses REQUIRED)
and it will work perfectly :)
|
71,835,065 | 71,835,136 | Is it better to have one large file or many smaller files for data storage? | I have an C++ game which sends a Python-SocketIO request to a server, which loads the requested JSON data into memory for reference, and then sends portions of it to the client as necessary. Most of the previous answers here detail that the server has to repeatedly search the database, when in this case, all of the data is stored in memory after the first time, and is released after the client disconnects.
I don't want to have a large influx of memory usage whenever a new client joins, however most of what I have seen points away from using small files (50-100kB absolute maximum), and instead use large files, which would cause the large memory usage I'm trying to avoid.
My question is this: would it still be beneficial to use one large file, or should I use the smaller files; both from an organization standpoint and from a performance one?
|
Is it better to have one large file or many smaller files for data storage?
Both can potentially be better. Each have their advantage and disadvantage. Which is better depends on the details of the use case. It's quite possible that best way may be something in between such as a few medium sized files.
Regarding performance, the most accurate way to verify what is best is to try out each of them and measure.
|
71,835,076 | 71,835,099 | Turning an unsigned integer into a double from 0 to 1. Dividing by integer limit not working | So I'm wanting to turn an unsigned integer (Fairly large one, often above half of the unsigned integer limit) into a double that shows how far it is between 0 and the unsigned integer limit. Problem is, dividing it by the unsigned integer limit is always returning 0. Example:
#include <iostream>
;
int main()
{
uint64_t a = 11446744073709551615
double b = a / 18446744073709551615;
std::cout << b;
};
This always returns 0. Is there an alternative method or a way to fix this one?
If it means anything, I'm using GCC with the -O3 optimisation flag.
| You have to convert the expression on the right to double, for example, like this:
double b = static_cast<double>(a) / 18446744073709551615;
or
double b = a / 18446744073709551615.0;
|
71,835,581 | 71,835,631 | strange std::list iteration behavior | #include <list>
#include <iostream>
#include <utility>
#include <conio.h>
std::list<int>&& asd()
{
std::list<int> a{ 4, 5, 6 };
return std::move( a );
}
int main()
{
std::list<int> a{ 1, 2, 3 };
std::list<int> &&b = std::move( a );
for( auto &iter : b )
{ std::cout<<iter<<' '; }
std::list<int> &&c{ asd() };
for( auto &iter : c )
{ std::cout<<iter<<' '; _getch(); }
}
this is what my program outputs:
1 2 3
4 3502376 454695192 3473720 4 3502376 454695192 3473720 4 3502376 454695192 3473720 4
| std::list<int> a{ 4, 5, 6 };
This object is declared locally inside this function, so it gets destroyed when the function returns.
std::list<int>&& asd()
This function returns an rvalue reference. A reference to some unspecified object.
What happens here is that this "unspecified object" gets destroyed when this function returns, so the caller ends up holding a reference to a destroyed object.
return std::move( a );
The dirty little secret is that std::move() does not actually move anything. It never did, it never will. All that std::move() does is cast its parameter into an rvalue reference. Whether the object gets moved, or not, requires other dominoes to fall into place. std::move() merely provides one piece of the puzzle, but all other pieces of this puzzle must exist in order for an actual move to happen.
Here, those other pieces of the puzzle do not exist. Therefore, nothing gets moved. A reference to a destroyed object gets returned, and all subsequent use of the destroyed object results in undefined behavior.
|
71,835,751 | 71,838,877 | How do I unit test and check the contents of a vector object of a custom struct using google mock? | If the structure is
struct Point{
double x;
double y;
};
and the output of a function is vector<Point> and has a size of 10, how do I write a Google Test or Google Mock(I think this is more suitable for this) to verify the contents of the vector? I can write the expected output in a Raw string.
| To start of: it's fine to just write you assertions by hand, checking the size and the content element by element:
std::vector<Point> MethodReturningVector();
TEST(MethodReturningVectorTest, CheckSizeAndFirstElementTest) {
const auto result = MethodReturningVector();
ASSERT_EQ(10, result.size());
ASSERT_NEAR(42.f, result[0].x, 0.001f);
ASSERT_NEAR(3.141592.f, result[0].y, 0.001f);
}
once you write a lot of different test you'll see a common pattern of the assertions and then you can refactor your tests and it all will fall in place naturally.
But as you mentioned GMock, indeed there are some GMock techniques that you can use. There are in-built matchers to match STL-like arrays (I say STL-like because it is only required that begin and end), e.g. ElementsAre (ElementsAreArray also exists). However, they require that the elements inside the array can be compared. This in turn requires that operator== is defined for your type (rarely is) because the default Eq matcher is using it. You can define your own matchers for custom types using another in-built matchers like AllOf (aggregator of matchers) and Field (matching given field of a struct). The matchers can get combined. For full picture see (working example):
struct Point{
double x;
double y;
};
std::vector<Point> MethodReturningVector() {
std::vector<Point> result(3);
result[0] = Point{42.f, 3.141592f};
return result;
}
MATCHER_P(Near, expected, "...") {
constexpr auto allowed_diff = 0.001f; // allow small diference
if (!(expected - arg <= allowed_diff && arg <= expected + allowed_diff)) {
*result_listener << "expected: " << expected << ", actual: " << arg;
return false;
}
return true;
}
auto MatchPoint(Point p) {
return testing::AllOf(testing::Field(&Point::x, Near(p.x)),
testing::Field(&Point::y, Near(p.y)));
}
TEST(MethodReturningVectorTest, TestOneElement)
{
const auto result = MethodReturningVector();
ASSERT_EQ(result.size(), 3);
ASSERT_THAT(result[0], MatchPoint(Point{42.f, 3.1415}));
}
TEST(MethodReturningVectorTest, TestWholeArray)
{
const auto result = MethodReturningVector();
ASSERT_THAT(result, testing::ElementsAre(
MatchPoint(Point{42.f, 3.1415f}),
MatchPoint(Point{0.f, 0.f}),
MatchPoint(Point{0.f, 0.f})));
}
I strongly suggest you start with GTest/GMock cookbook etc.
|
71,835,844 | 71,835,964 | Does memcpy preserve a trivial object's validity? | If one has a valid object of a trivial type (in this context, a trivial type satisfies the trivially move/copy constructible concepts), and one memcpys it to a region of uninitialised memory, is the copied region of memory a valid object?
Assumption from what I've read: An object is only valid if it's constructor has been called.
| Copying an object of a trivial type with std::memcpy into properly sized and aligned storage will implicitly begin the lifetime of a new object at that location.
There is a category of types called implicit-lifetime type whose requirements are :
a scalar type, or
an array type, or
an aggregate class type, or
a class type that has
at least one trivial eligible constructor, and
a trivial, non-deleted destructor,
or a cv-qualified version of one of above types.
Trivial class types meet these requiements.
Objects of implicit-lifetime type have the property that their lifetime can be started implicitly be several functions or operations :
operations that begin lifetime of an array of type char, unsigned char, or std::byte, (since C++17) in which case such objects are created in the array,
call to following allocating functions, in which case such objects are
created in the allocated storage:
operator new
operator new[]
std::malloc
std::calloc
std::realloc
std::aligned_alloc (since C++17)
call to following object representation copying functions, in which case such objects are created in the destination region of storage or the result:
std::memcpy
std::memmove
std::bit_cast (since C++20)
|
71,836,532 | 71,836,851 | How to get rid of incompatible c++ conversion | I'm getting the following error during compilation:
Severity Code Description Project File Line Suppression State
Error C2664 'mytest::Test::Test(const mytest::Test &)': cannot convert argument 1 from '_Ty' to 'const mytest::Test &' TotalTest C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\include\xutility 158
I have no idea what is, so I'm putting the code here to exemplify what was being done:
TotalTest.cpp
include <iostream>
#include "Test.h"
using namespace mytest;
int main()
{
std::cout << "Hello World!\n";
new Test();
}
Test.h
#pragma once
#include "Test.h"
#include <iostream>
namespace mytest
{
using namespace std;
class Test
{
public:
Test();
~Test();
shared_ptr<Test> t;
};
}
Test.cpp
#include "Test.h"
namespace mytest
{
Test::Test()
{
}
Test::~Test()
{
}
}
TestFactory.h
#pragma once
#include "Test.h"
#include <iostream>
namespace mytest
{
using namespace std;
class TestFactory
{
public:
TestFactory();
shared_ptr<Test> CreateTest(int testClass);
};
}
TestFactory.cpp
#include "TestFactory.h"
namespace mytest
{
TestFactory::TestFactory()
{
}
shared_ptr<Test> TestFactory::CreateTest(int testClass)
{
return make_shared<Test>(new Test());
}
}
I'm using Visual Studio C++ language standard: ISO C++14 Standard (/std:c++14)
| In TestFactory::CreateTest(), make_shared<Test>(new Test()) is wrong, as Test does not have a constructor that accepts a Test* pointer as input.
You need to use make_shared<Test>() instead, letting make_shared() call the default Test() constructor for you:
shared_ptr<Test> TestFactory::CreateTest(int testClass)
{
return make_shared<Test>();
}
Any parameters you pass to make_shared() are passed to the constructor of the type specified in the template argument. In this case, there are no parameters needed.
|
71,836,535 | 71,836,944 | The c++ 20 way to parse a simple delimited string | There are plenty of questions and answers here on how to parse delimited strings. I am looking for c++20 ish answers. The following works, but it feels lacking. Any suggestions to do this more elegantly?
const std::string& n = "1,2,3,4";
const std::string& delim = ",";
std::vector<std::string> line;
for (const auto& word : std::views::split(n, delim)) {
line.push_back(std::string(word.begin(), word.end()));
}
| There is no need to create substrings of type std::string, you can use std::string_view to avoid unnecessary memory allocation.
With the introduction of C++23 ranges::to, this can be written as
const std::string& n = "1,2,3,4";
const std::string& delim = ",";
const auto line = n | std::views::split(delim)
| std::ranges::to<std::vector<std::string_view>>();
Demo
|
71,836,992 | 71,837,585 | Why My output is printing # in Huffman coding | So I was implementing Huffman coding problem in which i wrote the below code and below is the output attached. Can any one tell me why I am getting # in the output:-
#include<bits/stdc++.h>
using namespace std;
class HuffTree
{
public:
int val;
char letter;
HuffTree* left, * right;
HuffTree(int val, char letter)
{
this->val = val;
this->letter = letter;
this->left = nullptr;
this->right = nullptr;
}
};
vector<pair<int, char>> FrequencyCount(string s)
{
map<char, int> mp;
for (int i = 0;i < s.size();i++)
mp[s[i]]++;
vector<pair<int, char>> v;
for (auto it : mp)
v.push_back(make_pair(it.second, it.first));
return v;
}
class Compare
{
public:
bool operator() (HuffTree* a, HuffTree* b)
{
return (a->val > b->val);
}
};
vector<pair<char, string >> huffmannCodes;
void printCodes(HuffTree* root, string str)
{
if (!root)
return;
if (root->val != '#')
huffmannCodes.push_back(make_pair(root->letter, str));
printCodes(root->left, str + "0");
printCodes(root->right, str + "1");
}
void makeTree(vector<pair<int, char>>& frq)
{
priority_queue<HuffTree*, vector<HuffTree*>, Compare> pq;
for (auto it : frq)
pq.push(new HuffTree(it.first, it.second));
while (pq.size() > 1)
{
HuffTree* left = pq.top();
pq.pop();
HuffTree* right = pq.top();
pq.pop();
HuffTree* newNode = new HuffTree(left->val + right->val, '#');
newNode->left = left;
newNode->right = right;
pq.push(newNode);
}
printCodes(pq.top(), "");
}
int main()
{
string s;
cin >> s;
vector<pair<int, char>> freqcount = FrequencyCount(s);
sort(freqcount.begin(), freqcount.end());
makeTree(freqcount);
for (auto it : huffmannCodes)
cout << it.first << "-->" << it.second << endl;
}
When I run the program this is what i am getting in the output:-
output
Can Anyone tell me why my output contains # as the node.
Any help will be appreciated.
| if (root->val != '#') should be if (root->letter != '#').
|
71,838,930 | 71,839,908 | Singleton over microcontroller | I am trying to use Singleton pattern in an embedded project, but I can't compile the project. The class, now, is very simple and I don't understand the problem.
The error is (48, in my code is the last line of instance function):
RadioWrapper.h:48: undefined reference to `RadioWrapper::mInstance'
Any ideas?
#define RADIOWRAPPER_H_
class RadioWrapper
{
protected:
RadioWrapper() {};
~RadioWrapper() { mInstance = NULL;}
public:
static RadioWrapper* instance (void)
{
if (!mInstance)
{
mInstance = new RadioWrapper();
return mInstance;
}
else
{
return mInstance;
}
}
void setRx (void);
private:
static RadioWrapper* mInstance;
};
#endif /* RADIOWRAPPER_H_ */
| A static member of a class, like static RadioWrapper* mInstance,
has to be defined (what you have in the H file is a declaration only).
You need to add:
/*static*/ RadioWrapper::mInstance = nullptr;
(the /*static*/ prefix is for documentation only).
This should be added in a CPP file, not H file (otherwise if the H file is included more than once, you'll have multiple definitions.)
If you are using C++ 17, you can use an inline variable that can be defined and initialized in the H file. See the 2nd answer here: How to initialize static members in the header
|
71,839,320 | 71,840,214 | Storing data from a file into array C++ | I would like to store the below txt file into a few arrays using C++ but I could not do it as the white space for the item name will affect the storing.
Monday //store in P1 string
14-February-2022 //store in P2 string
Red Chilli //store in P3 array, problem occurs here as i want this whole line to be store in the array
A222562Q //store in P4 array
1.30 2.00 //store in P5 and P6 array
Japanese Sweet Potatoes //repeat storing for Item 2 until end of the file
B807729E
4.99 1.80
Parsley
G600342k
15.00 1.20
Below is the coding I have tried to do to store the data in the array. It might not be the best way. Can provide me a better ways to store the data. Thanks
ifstream infile;
infile.open("itemList.txt");
infile >> P1;
infile >> P2;
for (int i = 0; i < sizeof(P3); i++) {
infile >> P3[i];
infile >> P4[i];
infile >> P5[i];
infile >> P6[i];
}
| You can use std::getline instead of the operator>> for the P3 field:
constexpr int NumOfEntries = 3;
std::array<std::string, NumOfEntries> P3;
// ... and assuming P4, P5, P6 are declared similarly above
for (int i = 0; i < NumOfEntries; i++) {
std::getline(infile, P3[i]);
infile >> P4[i];
infile >> P5[i];
infile >> P6[i];
infile.ignore();
}
You don't show the definitions of P3 to P6, and the i < sizeof(P3) condition in your for loop looks strange - I can't come up with a declaration for P3 for which that loop would then work properly. But apparently you already know before how many entries there are in the file, right? So I use std::vector<std::string> for P3, and a constant NumOfEntries for the loop condition.
cin.ignore() is required to ignore the newline character after P6 input; otherwise the next getline would only deliver an empty string in its next turn. See for example this other question for more details.
|
71,839,353 | 71,839,436 | Implicit cast to size_t? | I want to know - does C++ do implicit cast when we initialize unsigned size_t with some value?
Like this:
size_t value = 100;
And does it make sense to add 'u' literal to the value to prevent this cast, like this?
size_t value = 100u;
|
does C++ do implicit cast when we initialize unsigned size_t with some
value? Like this:
size_t value = 100;
Yes. std::size_t is an (alias of an) integer type. An integer type can be implicitly converted to all other integer types.
And does it make sense to add 'u' literal to the value to prevent this cast, like this?
There is still likely an implicit conversion with the u literal suffix since std::size_t is not necessarily (nor typically) unsigned int. It may be for example unsigned long int or unsigned long long int. There is a standard proposal to add integer literal for the std::size_t alias, but there doesn't exist one for now.
Using a matching literal doesn't matter much in this example, as long as the type of the literal can represent the value in question, and as long as the literal value doesn't exceed the bounds of the initialised type. Even the smallest integer types can represent 100. The choice is largely a matter of taste.
Note that "implicit cast" is a contradiction in terms. Cast is an explicit conversion.
|
71,839,364 | 71,839,459 | c++ template type pack specialization for tuple | When trying to implement a tuple type i run into the problem an empty tuple.
This is the type structure i used:
template <class T, class... Ts>
struct Tuple : public Tuple<Ts...> {};
template <class T>
struct Tuple {};
As soon as i try to add an overload for no type the compiler complains: Too few template arguments for class template 'Tuple':
template <> struct Tuple<> {};
I guess it's because the Tuple type was declared with at least one provided type at first and the compiler can't overload the same type with a different set of template parameters, but i wonder how i could solve this problem without completely restructuring my code.
My first idea was to define the tuple like template <class... Ts> struct Tuple {}; first and than add the other overloads, but the compiler than complains for to much template arguments.
| Your template expects at least one parameter. You can change it like this to allow zero or more:
template <typename ... Ts>
struct Tuple;
template <>
struct Tuple<> {};
template <class T,class... Ts>
struct Tuple<T,Ts...> : public Tuple<Ts...> {};
int main()
{
Tuple<int,int,double> t;
}
|
71,839,686 | 71,840,240 | Check if a path is valid, even if it doesn't exist | Let's say I have a program that takes paths to the input and output directories from a command line. If the output directory doesn't exist, our program needs to create it. I would like to check (preferably using std::filesystem) if that path is valid, before sending it to std::filesystem::create_directory().
What is the best way to do it?
| You gain nothing by doing (pseudo-code alert):
if (doesnt_exist(dir)) {
create_directory(dir);
}
Better to just do:
create_directory(dir);
And handle errors properly if necessary. You may not even need to handle errors here if you handle subsequent errors.
The "if exists" check introduces unnecessary complexity, and introduces a race condition. And even if the directory doesn't exist, you may still not have permission to create it. So in any case your error handling will be the same, rendering the "if exists" check completely pointless.
I guess it's another way of "don't ask permission, ask forgiveness" except with computers you don't need to ask forgiveness.
|
71,840,559 | 71,842,690 | Using AWS Cloudwatch to monitor C++ (on-premises, not cloud) program | I am trying to create a simple C++ program that sends something like a real-time status message to AWS CloudWatch to inform that it is up and running, and the status goes offline when it's closed (real-time online/offline status). The C++ program will be installed at multiple users' computers, so there will be like a dashboard on CloudWatch. Is this even possible? I'm lost on AWS between Alarms/Logs/Metrics/Events..etc.
I also want to send some stats from each PC where the program is installed, like CPU usage for example, is it possible to make a dashboard on CloudWatch to monitor this as well? Am I free to create dashboard with whatever data I want? All the tutorials I found talk about integrating CloudWatch with other AWS services (Like Lambda and EC2) which isn't my case.
Thank you in advance.
| The best way to monitor a process will be using AWS CloudWatch procstat plugin. First, create a CloudWatch configuration file with PID file location from EC2 and monitor the memory_rss parameter of the process. You can read here more.
For stats you can install CloudWatch Agent on each machine and collect necessary metrics. You can read here more.
|
71,840,940 | 71,841,195 | The dfs is not wroking | The problem I am seeing is that it outputted all of the ways, even the ones that cannot reach the end. But that is not how DFS is supposed to work.
As I know right now, DFS is within a recursive call chain, and when it goes deeper into the function, it should remove the ones that are not correct and keep the ones that are correct.
Here is the code:
#include <iostream>
#define ll long long
using namespace std;
bool f = false;
ll map[10001][10001];
ll vis[10001][10001];
char endmap[10001][10001];
ll dx[] = {0 , 0 , 1 , -1};
ll dy[] = {-1, 1 , 0, 0};
ll n,m,x1,y1,x2,y2;
void dfs(ll fi, ll fj){
if(fi == x2&&fj == y2){
cout << "PATH FOUND!:" << endl;
f = true;
for(ll i1 = 1; i1<=n; i1++){
for(ll j1 = 1; j1<= m; j1++){
if(vis[i1][j1] == 1){
endmap[i1][j1] = '!';
}
}
}
endmap[1][1] = 'S';
endmap[x2][y2] = 'E';
for(ll i1 = 1; i1<=n; i1++){
for(ll j1 = 1; j1<= m; j1++){
cout << endmap[i1][j1] << " ";
}
cout << endl;
}
system("pause");
exit(0);
}else{
for(ll i = 0; i<4; i++){
ll xx = fi + dx[i];
ll yy = fj + dy[i];
if (yy>=1&& xx >= 1 && vis[xx][yy] == 0 && xx <= n && yy <= n && map[xx][yy] == 0){
vis[xx][yy] = 1;
dfs(xx,yy);
}
}
}
}
int main(){
cout << "Enter the length and the width of the map: ";
cin >> n >> m;
for(ll i = 1; i<=n; i++){
for(ll j = 1; j<=m; j++){
endmap[i][j] = '0';
}
}
cout << "Draw the map: " << endl;
for(ll i = 1; i<=n; i++){
for(ll j = 1; j<=m; j++){
cin >> map[i][j];
}
}
cout << "Enter the start(two numbers) and the end(two numbers):";
cin >> x1 >> y1 >> x2 >> y2;
cout << endl << "EXECUTING..." << endl;
dfs(x1,y1);
if(!f){
cerr << "ERROR! " << "Found on: " << __TIME__ << endl << "NO EXIT/PATH FOUND!" << endl;
}
return 0;
}
The input is like this:
Enter the length and the width of the map: 9 9
Draw the map:
0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1
1 0 1 1 1 1 1 0 1
1 0 0 0 1 0 0 0 1
1 0 1 0 1 0 1 0 1
1 0 0 1 1 1 1 0 1
1 1 0 1 1 1 1 1 1
1 1 0 0 0 0 1 1 1
1 1 1 1 1 0 0 0 0
Enter the start(two numbers) and the end(two numbers):1 1 9 9
And the output:
EXECUTING...
PATH FOUND!:
S 0 0 0 0 0 0 0 0
! ! ! ! ! ! ! ! 0
0 ! 0 0 0 0 0 ! 0
0 ! ! ! 0 ! ! ! 0
0 ! 0 ! 0 ! 0 ! 0
0 ! ! 0 0 0 0 ! 0
0 0 ! 0 0 0 0 0 0
0 0 ! ! ! ! 0 0 0
0 0 0 0 0 ! ! ! E
Does anyone know why this is happening?
| Herein lies the problem, all locations visited by DFS are marked:
if(vis[i1][j1] == 1){
endmap[i1][j1] = '!';
}
You should record the current path with a data structure (such as vector) in the DFS input parameter, and when DFS can reach the end, mark all coordinates in the vector with an exclamation point.
|
71,841,083 | 71,841,348 | Implementation of typed tuple wrapper | How can an implementation look like, that wraps around e.g. a std::tuple as a static list of type/value, plus a type (not contained in tuple) to refer to some kind of owner/visitor.
I want to instantiate like
constexpr auto data = data_of<a>(1, 2.0);
Background
The idea is to use a data_of<T>(...) kind of structure to to pass a list of type/data pairs into a bulk function like this.
template <typename... _Ts>
static constexpr void do_bulk_stuff(_Ts&&... _Vs)
{
// crazy stuff happens here
}
// call it like
do_bulk_stuff
(
data_of<a>(1, 2.0),
data_of<b>(3),
data_of<c>(4.0, 5, 6),
// ...
);
Attempt 1
So far I ended up with a naive (not working) implementation attempt like
template <typename T, typename... Ts>
struct data_of {
using type = T;
using data_t = std::tuple<Ts...>;
data_t data;
constexpr data_of(Ts&&... Vs)
: data(Vs...)
{}
};
Goal
My goal is to achieve a result like this data_of<a> instance pseudo code example
{
// meta
type = a;
data_t = std::tuple<int,double>;
// runtime
data = [1, 2.0];
}
| The issue inherent to your attempt is that class template argument deduction is simply not like its function counterpart. There will be no deduction if any of the class template's arguments is explicitly specified. You fail because the trailing pack is always specified (by omission) as empty.
The solution is to shift the burden onto the mechanism that allows you to specify only part of the arguments: function templates.
template <typename T, typename... Ts>
struct data_of_t {
using type = T;
using data_t = std::tuple<Ts...>;
data_t data;
constexpr data_of_t(Ts&&... vs)
: data(std::forward<Ts>(vs)...)
{}
};
template<typename T, typename... Ts>
constexpr auto data_of(Ts&&... vs) {
return data_of_t<T, Ts...>(std::forward<Ts>(vs)...);
}
Now the type of the expression data_of<a>(1, 2.0) has the same "meta" properties you are after.
|
71,841,381 | 71,841,655 | range-based for loop and std::transform with input/output iterators not equivalent when applied to rows of opencv Mat(rix) | In a larger program, I came across the following problem, which I do not understand.
Basically, I am processing an opencv matrix of type float (cv::Mat1f) (docs here). OpenCV provides iterators to iterate over a matrix. When I iterate over the matrix using range-based iterators and a reference to the matrix members, the code works (test1 in the example below).
When I use std::transform and apply it to the entire matrix, the code below (test3) also works.
However, when I do the iteration row-wise, then the version with std::transform fails (it never (?) terminates).
(The reason I work on rows is that in the real application rows are processed in different parallel threads, but that is of no concern here)
#include <iostream>
#include "opencv2/imgproc.hpp"
void test1(cv::Mat1f& img) {
for (int r = 0; r < img.rows; r++)
for (auto& v : img.row(r))
v = v+1;
}
void test2(cv::Mat1f& img) {
for (int r = 0; r < img.rows; r++)
std::transform(
img.row(r).begin(),
img.row(r).end(),
img.row(r).begin(),
[](float v)->float { return v+1; });
}
void test3(cv::Mat1f& img) {
std::transform(
img.begin(),
img.end(),
img.begin(),
[](float v)->float { return v+1; });
}
int main() {
auto img = cv::Mat1f(5, 5, 0.0);
int i = 0;
for (auto &v : img)
v = i++;
std::cerr << img << "\n";
test1(img);
std::cerr << img << "\n";
// test2(img); does not work
test3(img); // works !
std::cerr << img << "\n";
}
On my system (with opencv installed in /usr/local) I run the example code above with
g++ -std=c++17 -I/usr/local/include/opencv4 mwe.cpp -L/usr/local/lib -lopencv_core && ./a.out
What is wrong with the code in test2 ?
| Each call to row creates a new object, and these objects have distinct iterators.
So, row(r).begin() will never be equal to row(r).end().
Get the iterators from the same object instead:
void test2(cv::Mat1f& img) {
for (int r = 0; r < img.rows; r++)
auto row = img.row(r);
std::transform(
row.begin(),
row.end(),
row.begin(),
[](float v)->float { return v+1; });
}
|
71,841,567 | 71,842,877 | std::variant and ambiguous initialization | Consider the following code:
void fnc(int)
{
std::cout << "int";
}
void fnc(long double)
{
std::cout << "long double";
}
int main()
{
fnc(42.3); // error
}
It gives an error because of an ambiguous call to fnc.
However, if we write the next code:
std::variant<int, long double> v{42.3};
std::cout << v.index();
the output is 1, which demonstrates that the double->long double conversion has been chosen.
As far as I know, std::variant follows the C++ rules about conversion ranks, but this example shows the difference. Is there any explanation for such a behavior?
| Before P0608, variant<int, long double> v{42.3} also has the ambiguous issue since 42.3 can be converted to int or long double.
P0608 changed the behavior of variant's constructors:
template<class T> constexpr variant(T&& t) noexcept(see below);
Let Tj be a type that is determined as follows: build an imaginary function FUN(Ti) for each alternative type Ti for which Ti x[] = {std::forward<T>(t)}; is well-formed for some invented variable x and,
if Ti is cv bool, remove_cvref_t<T> is bool. The overload FUN(Ti)
selected by overload resolution for the expression
FUN(std::forward<T>(t)) defines the alternative Tj which is the type
of the contained value after construction.
In your example, the variant has two alternative types: int and long double, so we can build the following expression
int x[] = {std::forward<double>(42.3)}; // #1
long double y[] = {std::forward<double>(42.3)}; // #2
Since only #2 is well-formed, the variant successfully deduces the type of the contained value type long double.
|
71,841,608 | 71,842,030 | The actual and formal parameters of the array use the same block address, while the variables use different addresses | When using the address transfer of function, View address blocks of formal parameters and actual parameters, I find that the arguments and formal parameters of array share one address block, while the arguments and formal parameters of variables use two address block. What is the reason?
The code is as follows:
#include<iostream>
using namespace std;
void test(int *i,int * arr) {
cout << &i << endl;
cout << arr << endl;
}
int main() {
int i = 1, arr[2] = {1,2};
cout << &i << endl;
test(&i, arr);
cout << arr << endl;
system("pause");
return 0;
}
And this is the output:
0000008986B6FC54
0000008986B6FC30
0000008986B6FC78 //Arrays use the same space
0000008986B6FC78
| You are passing pointers to the functions. The value of the pointers are not modified, ie in the function they point to the same objects as they do in main.
However, you are not printing what you think you print:
void test(int *i,int * arr) {
cout << &i << endl;
cout << arr << endl;
}
The pointer i gets the parameter &i (the i from main). Hence printing i in main will yield the same value as printing i in test. However, you are printing the adress of i in the function not the value of it. If you change your code to:
void test(int *i,int * arr) {
cout << &i << endl;
cout << i << endl;
cout << arr << endl;
}
You will notice the difference. I suggest you to rename at least one of the is in your code, because using same name for different entities can and does cause confusion. The i in test holds the value of the address of the i in main. That does not mean that they are the same, but rather i in test has the same value as &i in main.
In short: &i == &i but you expect &(&i) to be the same as &i.
There is no difference between passing a pointer to the int or passing a pointer to the first element of the array. From the point of view of the function they are both just pointers to int.
|
71,841,726 | 71,841,904 | How C/C++ compiler distinguish regular two dimensional array and array of pointers to arrays? | Regular static allocated array looks like this, and may be accessed using the following formulas:
const int N = 3;
const int M = 3;
int a1[N][M] = { {0,1,2}, {3,4,5}, {6,7,8} };
int x = a1[1][2]; // x = 5
int y = *(a1+2+N*1); // y = 5, this is what [] operator is doing in the background
Array is continuous region of memory. It looks different in case of dynamic array allocation, there is array of pointer to arrays instead:
int** a2 = new int*[N];
for (int i = 0; i < N; i++)
a2[i] = new int[M];
//Assignment of values as in previous example
int x = a2[1][2];
int y = *(*(a2+1))+2); // This is what [] operator is doing in the background, it needs to dereference pointers twice
As we can see, operations done by [] operator are completely different in case of typical continuous array and dynamically allocated array.
My questions are now following:
Is my understanding of [] operations correct?
How C/C++ compiler can distinguish which [] operation it should perform, and where it's implemented? I can image implementing it myself in C++ by overloading [] operator, but how C/C++ treat this?
Will it work correctly in C language using malloc instead of new? I don't see any reasons why not actually.
| For this declaration of an array
int a1[N][M] = { {0,1,2}, {3,4,5}, {6,7,8} };
these records
int x = a1[1][2];
int y = *(a1+2+N*1);
are not equivalent.
The second one is incorrect. The expression *(a1+2+N*1) has the type int[3] that is implicitly converted to an object of the type int * used as an initializer. So the integer variable y is initialized by a pointer.
The operator a1[1] is evaluated like *( a1 + 1 ) . The result is a one-dimensional array of the type int[3].
So applying the second subscript operator you will get *( *( a1 + 1 ) + 2 ).
The difference between the expressions when used the two-dimensional array and the dynamically allocated array is that the designator of the two-dimensional array in this expression (a1 + 1) is implicitly converted to a pointer to its first element of the type int ( * )[3] while the pointer to the dynamically allocated array of pointers still have the same type int **.
In the first case dereferencing the expression *(a1 + 1 ) you will get lvalue of the type int[3] that in turn used in the expression *( a1 + 1) + 2 is again implicitly converted to a pointer of the type int *.
In the second case the expression *(a1 + 1) yields an object of the type int *.
In the both cases there is used the pointer arithmetic. The difference is that when you are using arrays in the subscript operator then they are implicitly converted to pointers to their first elements.
When you are allocating dynamically arrays when you are already deals with pointers to their first elements.
For example instead of these allocations
int** a2 = new int*[N];
for (int i = 0; i < N; i++)
a2[i] = new int[M];
you could just write
int ( *a2 )[M] = new int[N][M];
|
71,842,109 | 71,842,349 | C++ possible to create macros with non-alpha names? | Is it possible to make preporcessor to replace an arbitrary string with an arbitrary string?
I would like to replace {+} with {:.{}}
|
C++ possible to create macros with non-alpha names?
I would like to replace {+} with {:.{}}
No, you cannot achieve this using the standard pre-processor. Macro names are identifiers. Identifiers may contain digits (except first char), latin alphabet, underscore, and characters in XID_Start/XID_Continue classes.
P.S. Consider avoiding pre-processor macros when possible.
|
71,842,175 | 71,842,327 | How to search a file using an array as search term | I'm trying to parse a csv file and search it to find values that match my randomly generated array.
I've tried a few methods but im getting lost, I need to access the entire file, search for these values and output the index column that it belongs to.
my code for my random array generator as well as my search csv function:
EDIT:
edited code to make reproducible, with added comments, hopefully this matches criteria (besides given csv file obviously).
reproducible example:
#include <fstream>
#include <iostream>
#include <string>
#include <random>
using namespace std;
//fills array of size 6 with random numbers between 1-50
void random_array(int arr[]){
for(int i=0;i<6;i++)
{
int num = rand()%51;
arr[i]=num;
}
}
int main(){
string line;
fstream file;
int size = 6;
int numbers[size];
int found;
//gets random array from random_array func
srand(time(NULL));
random_array(numbers);
//opens file to search
file.open("CSV directory here");
if(file.is_open())
{
//print random array values
for(int i = 0; i < size; i++){
cout << numbers[i]<< " ";}
cout << endl;
//get file contents and search if contents of array exist in file
while(getline(file, line)){
for(int i = 0; i < size; i++){
found = line.find(std::to_string(numbers[i]));
if(found != string::npos) {
//print found numbers
cout << found << " ";
}
}
}
}
return 0;
}
CSV format:
,Date,1,2,3,4,5,6,7
0,Wed 03 January 2001,5,6,16,17,19,22,40
1,Sat 06 January 2001,6,16,23,34,35,40,37
my output:
array generated:
35 35 38 37 16 31
numbers found:
26 33 33 39 24 31 34 33 24 6 28 31 33 33 30 0 32 34 33 30 27 38 26 29
29 33 7 24 29 26 26 26 24 24 0 30 30 36 0 0 23 27 0 0 7 36 36 27 30 30
27 27 26 26 32 29 23 38 32 32 28 28 7 25 29 37 25 29 29 26 23 34 31 28
25 31 28 28 34 32 32 35 38 40 25 37 37 35 40 40 30 30 42 42 42 36 35
28 31 25 37 7 27 36 33 36 33 29 39 29 35 34 34 40 40 43 31
| I'd recommend looking at the find function in more detail. None of its overloads take in an integer, the nearest match (and one that would be used) takes in a char ... So it would not be looking for strings like "12" it would be looking for the character which has a value of 12.
You need to first convert the number(s) to a string. A simple modification would be:
for ( int i = 0; i < 6; i++ ) {
if( (offset = line.find( std::to_string( numbers[i] ) ) ) != string::npos ) {
//do something
}
}
|
71,842,556 | 71,842,691 | Why is there a narrowing conversion warning from int to short when adding shorts? (C++) | I have a code similar to this for the following array:
long int N = 424242424242; //random number
short int* spins = new short int spins[N];
std::fill(spins, spins+N, 1);
Now let's suppose for some reason I want to add a couple of elements of that array into a short int called nn_sum:
short int nn_sum = spins[0] + spins[1];
However, when I do this on CLion IDE, Clang-Tidy marks it yellow and tells me:
Clang-Tidy: Narrowing conversion from 'int' to signed type 'short' is implementation-defined
Why is this happening? Why is there any narrowing at all? Does C++ convert the shorts to ints when adding them? If so why, and is there something I can do to make it work better? Maybe even ditch the shorts entirely?
Keep in mind that I have code like this in a very computationally intensive part of the application so I want to make it as efficient as possible. Any other suggestion would also be appreciated.
| This happens because of integer promotion. The result of adding two short values is not short, but int.
You can check this with cppinsights.io:
short a = 1;
short b = 2;
auto c = a + b; // c is int
Demo: https://cppinsights.io/s/68e27bd7
|
71,843,080 | 71,843,175 | end_unique algorithm, element disappear | #include <iostream>
#include <string>
#include <vector>
#include <list>
#include <iterator>
#include <algorithm>
using namespace std;
void elimdups(vector<string>& words) {
sort(words.begin(), words.end());
for(auto a : words)
{
cout << a << " ";
}
cout << endl;
auto end_unique = unique(words.begin(), words.end());
for (auto a : words)
{
cout << a << " ";
}
cout << endl;
words.erase(end_unique, words.end());
for (auto a : words)
{
cout << a << " ";
}
cout << endl;
}
int main()
{
vector<string> kim = { "love", "peace", "horrible", "love", "peace", "hi", "hi" };
elimdups(kim);
return 0;
}
--
result:
hi hi horrible love love peace peace
hi horrible love peace love peace
hi horrible love peace
end_unique algorithm do not delete elements.
but on the second cout operation, "hi" disappear.
why "hi" disappear on the second line?
| auto end_unique = unique(words.begin(), words.end());
for (auto a : words)
//...
Any items from [end_unique, words.end()) have unspecified values after the call to std::unique. That's why the output in the "erased" range seems strange.
If you want to preserve the "erased" words and keep the relative order, std::stable_partition with the appropriate lambda that checks duplicates could have been done.
|
71,843,100 | 71,843,166 | Get the length of an template<typename> array in c++ | I am trying to figure out how i get the length of an array in c++ without iterate over all index. The function looks like this:
template<typename T>
void linearSearch(T arr[], int n)
{
}
| You can't. T arr[] as argument is an obfuscated way to write T* arr, and a pointer to first element of an array does not know the arrays size.
If possible change the function to pass the array by reference instead of just a pointer:
template <typename T, size_t N>
void linearSearch(T (&array)[N], int n);
Things get much simpler if you use std::array.
PS: As a comment on the question suggests, the question is not quite clear. Is this the function you want to call after getting the size or do you need to get the size inside this function? Anyhow, I assumed the latter and that n is a argument unrelated to the arrays size. Further note that there is std::size that you can use to deduce the size also of a c-array. However, this also only works with the array, not once the array decayed to a pointer (as it does when passed as parameter to the function you posted).
|
71,843,222 | 71,843,359 | Compile-time error in uninstanciated function template | My understanding of function templates has always been: if they contain invalid
C++ and you don't instanciate them, your project will compile fine.
However, the following code:
#include <cstdio>
#include <utility>
template <typename T>
void contains_compile_time_error(T&& t) {
int j = nullptr;
}
int main() {}
Compiles with:
x86-64 gcc 11.2 and flag -std=c++20;
x64 msvc v19.31 and flag /std:c++20;
and does not with x86-64 clang 14.0.0 (with flags -std=c++{11,14,17,20}):
error: cannot initialize a variable of type 'int' with an rvalue of type 'std::nullptr_t'
int j = nullptr;
^ ~~~~~~~
1 error generated.
Even more confusing to me, the following code:
#include <cstdio>
#include <utility>
namespace ns {
struct S {};
template <typename T>
void apply(T&& t) {
//print(std::forward<T>(t));
ns::print(std::forward<T>(t));
}
void print(S const&) { std::puts("S"); }
} // namespace ns
int main() {}
Does not compile with:
x86-64 gcc 11.2 and flag -std=c++20;
x64 msvc v19.31 and flag /std:c++20;
x86-64 clang 14.0.0 and flags -std=c++{11,14,17,20};
(all of them complaining that print is not a member of 'ns') but does compile with x64 msvc v19.31 /std:c++17.
If I call unqualified print, then the code compiles with all the above compilers.
So, my questions are:
is my understanding of function templates wrong?
why do the above compilers behave differently with the code snippets I posted?
Edit 0: as per Frank's comment, x64 msvc v19.31 /std:c++17 /permissive- fails to compile function template apply where I call the qualified ns::print.
|
My understanding of function templates has always been: if they contain invalid C++ and you don't instanciate them, your project will compile fine.
Nope, if the code in the template is invalid, then so is the program.
But what does "invalid C++" mean? You can have syntactically valid C++ that is still invalid semantically, and the semantics of C++ are highly contextual.
So there's multiple levels of "valid" that can be checked at different times during compilation, based on the available information. Critically, there are things that can theoretically be checked early, but are potentially unreasonably difficult. Because of this, compilers are allowed some leeway when it comes to validating the semantics of template definitions. However, whether the code is broken or is not ambiguous, it's a compiler's ability to detect broken code that is.
why do the above compilers behave differently with the code snippets I posted?
As far as int j = nullptr is concerned:
The program is technically ill-formed, but the diagnostics is optional. So The code is broken, but GCC is not breaking compliance by letting it through.
For example, if S only had private constructors, then print(std::forward<T>(t)) would be flaggable as being broken since there is no possibly T that would make it valid. However, requiring compilers to be smart enough to determine this in all cases would be kind of mean.
For print():
Lookups are a bit of a different matter, there are hard rules that are supposed to be followed.
There are three types of lookups involved here.
Qualified lookups, such as ns::print
Unqualified lookups not involving template parameters, which you'd get if you tried print(S{});
Unqualified lookups involving template parameters, such as print(std::forward<T>(t));
Lookups are deferred for the third category, but must still be performed the same as non-template functions for the other two.
Note that the code still needs to be syntactically valid, even in the case of deferred lookups, hence why typename needs to be added when doing a dependent lookup of a type.
And as for MSVC allowing ns::print: That compiler is not compliant by default on this (and other) aspect of the standard. You need to use the /permissive- compiler flag to enforce compliance.
|
71,843,237 | 71,844,764 | OpenCV::LMSolver getting a simple example to run | PROBLEM: The documentation for cv::LMSolver at opencv.org is very thin, to say the least. Finding some useful examples on the internet, also, was not possible.
APPROACH: So, I did write some simple code:
#include <opencv2/calib3d.hpp>
#include <iostream>
using namespace cv;
using namespace std;
struct Easy : public LMSolver::Callback {
Easy() = default;
virtual bool compute(InputArray f_param, OutputArray f_error, OutputArray f_jacobian) const override
{
Mat param = f_param.getMat();
if( f_error.empty() ) f_error.create(1, 1, CV_64F); // dim(error) = 1
Mat error = f_error.getMat();
vector<double> x{param.at<double>(0,0), param.at<double>(1,0)}; // dim(param) = 2
double error0 = calc(x);
error.at<double>(0,0) = error0;
if( ! f_jacobian.needed() ) return true;
else if( f_jacobian.empty() ) f_jacobian.create(1, 2, CV_64F);
Mat jacobian = f_jacobian.getMat();
double e = 1e-10; // estimate derivatives in epsilon environment
jacobian.at<double>(0, 0) = (calc({x[0] + e, x[1] }) - error0) / e; // d/dx0 (error)
jacobian.at<double>(0, 1) = (calc({x[0], x[1] + e}) - error0) / e; // d/dx1 (error)
return true;
}
double calc(const vector<double> x) const { return x[0]*x[0] + x[1]*x[1]; }
};
int main(int argc, char** argv)
{
Ptr<Easy> callback = makePtr<Easy>();
Ptr<LMSolver> solver = LMSolver::create(callback, 100000, 1e-37);
Mat parameters = (Mat_<double>(2,1) << 5, 100);
solver->run(parameters);
cout << parameters << endl;
}
QUESTIONS:
What does the return value of LMSolver::Callback::compute() report to the caller?
Currently, it finds the minimum at (-9e-07,4e-5), instead of the expected (0.0, 0.0). How can the precision be improved?
|
What does the return value of LMSolver::Callback::compute() report to the caller?
Thankfully, opencv is opensource, so we might be able to figure this out simply by checking out the code.
Looking at the source code on Github, I found that all of the calls to compute() look like:
if( !cb->compute(x, r, J) )
return -1;
Returning false simply causes the solver to bail out. So it seems that the return value of the callback's compute() is simply whether the generation of the jacobian was successful or not.
Currently, it finds the minimum at (-9e-07,4e-5). How can the precision be improved?
If anything, you should at least compare the return value of run() against your maximum iteration count to make sure that it did, in fact, converge as much as it could.
|
71,843,879 | 71,844,202 | Weird symbols in copied/truncated character array | #include <iostream>
using namespace std;
void truncate(char* s1, char* s2, int n) {
for (int i = 0; i < n; i++) {
s2[i] = s1[i];
}
}
int main() {
char s1[15] = "Hello World";
char s2[10];
int n{ 5 };
truncate(s1, s2, n);
cout << s2; // this should display: Hello
}
When I run this in Visual Studio, I get this output:
Hello╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Hello World
But when I run it using an online compiler (Online GDB), the output is normal:
Hello
I know it has to do with the \0 terminator but I just can't figure it out.
| Your truncate function doesn't add the required nul terminator character to the destination (s2) string. Thus, when you call cout in main, that will keep printing characters until it finds its expected nul (zero) character at some unspecified location following the garbage-initialized data that pre-exists in the parts of the s2 local array that weren't explicitly set by your function. (This is undefined behaviour, and almost anything could actually be displayed; the program may also crash, if the cout call tries to read memory it doesn't have the required access to).
To correct this, simply add that nul (zero, or '\0') character to the end of the string in the truncate function. Assuming you don't go beyond the array's bounds, you can use the "left over" value of the loop index, i, to access the required element; but, to do so, you will need to declare the int i outside of the for loop's scope:
void truncate(char* s1, char* s2, int n)
{
int i; // Must be declared outside the FOR loop ...
for (i = 0; i < n; i++) {
s2[i] = s1[i];
}
s2[i] = '\0'; // ... so we can use it here.
}
Note: Another way (but apparently prohibited by your teacher) would be to set all elements of the s2 array in main to zero, before calling your truncate function:
char s2[10] = ""; // Set ALL elements to zero
Some compilers (seemingly including the online one you use) will "implicitly" set the elements of uninitialized local arrays to zero; but never rely on this: it is not part of the C++ Standard and compilers are not required to enforce such behaviour.
|
71,844,237 | 71,846,645 | c++ std::function callback | I have the below five files.
I am trying to call a function in two_b.cpp from one_a.cpp using a std::function callback, but I get the following error:
terminate called after throwing an instance of 'std::bad_function_call'
what(): bad_function_call
Aborted (core dumped)
one_a.h
#include <functional>
using CallbackType = std::function<void()>;
class Car {
public:
void car_run(void);
void car_stop(void);
CallbackType f1;
private:
CallbackType callbackHandler;
};
one_a.cpp
#include "one_a.h"
#include <iostream>
void Car::car_run(void)
{
std::cout<<"Car running"<<std::endl;
}
void Car::car_stop(void)
{
std::cout<<"Car stopping"<<std::endl;
}
two_b.h
#include "one_a.h"
class Boat {
public:
Boat(Car& car_itf);
static void boat_run(void);
static void boat_stop(void);
private:
Car& car_itf_;
};
two_b.cpp
#include "two_b.h"
#include <iostream>
Boat::Boat(Car& car_itf):car_itf_{car_itf}{
car_itf_.f1 = std::bind(&Boat::boat_run);
}
void Boat::boat_run(void)
{
std::cout<<"Boat running"<<std::endl;
}
void Boat::boat_stop(void)
{
std::cout<<"Boat running"<<std::endl;
}
main.cpp
#include "two_b.h"
int main()
{
Car bmw;
bmw.car_run();
bmw.f1();
return 0;
}
A running example can be found here:
https://www.onlinegdb.com/_uYHXfZsN
| std::function throws a std::bad_function_call exception if you try to invoke it without having a callable target assigned to it.
So, you need to actually assign a target to f1 before you try to invoke f1 as a function. You are doing that assignment in Boat's constructor, so you need to create a Boat object first, eg:
int main()
{
Car bmw;
Boat ferry(bmw); // <--
bmw.car_run();
bmw.f1();
return 0;
}
Online Demo
Also, make sure to clear f1 in Boat's destructor, so you don't leave the f1 dangling, eg:
Boat::~Boat(){
car_itf_.f1 = nullptr;
}
|
71,844,989 | 71,845,241 | How to wrap iterator of boost::circular_buffer? | I'm trying to use boost::circular_buffer to manage fixed size of the queue.
To do that, I wrap boost::circular_buffer by using class Something.
class Something {
public:
Something();
private:
boost::circular_buffer<int> buffer;
};
Here, the problem is that class Something should wrap iterator of buffer.
For example, If I use std::vector<int>, it is simple:
class Something {
public:
Something();
typedef std::vector<int>::iterator Iterator;
Iterator begin() { return buffer.begin(); }
Iterator end() { return buffer.end(); }
...
private:
std::vector<int> buffer;
};
How to use boost::circular_buffer to handle this?
| You can do the exact same thing as you do with the std::vector.
typedef std::vector<int>::iterator Iterator; declares a local type called Iterator that is an alias for std::vector<int>'s iterator type.
So logically, you should be able to just swap out the std::vector<int> for a boost::circular_buffer<int> and it should just drop in:
#include <boost/circular_buffer.hpp>
class Something {
public:
Something();
typedef boost::circular_buffer<int>::iterator Iterator;
Iterator begin() { return buffer.begin(); }
Iterator end() { return buffer.end(); }
private:
boost::circular_buffer<int> buffer;
};
You can clean this up further a bit by using a second type alias for the container itself. This way, you can change the container type by altering a single line of code, and everything else flows from there.
#include <boost/circular_buffer.hpp>
class Something {
public:
Something();
using container_type = boost::circular_buffer<int>;
using iterator = container_type::iterator;
iterator begin() { return buffer.begin(); }
iterator end() { return buffer.end(); }
private:
container_type buffer;
};
N.B. I used using instead of typedef since it's generally considered easier to read in modern code, but the meaning is the same.
|
71,844,996 | 71,846,759 | Use case for `&` ref-qualifier? | I just discovered this is valid C++:
struct S {
int f() &; // !
int g() const &; // !!
};
int main() {
S s;
s.f();
s.g();
}
IIUC, this is passed to f by reference and to g be passed by const-reference.
How was this useful to anyone?
| They are useful for both providing safety and optimizations.
For member functions returning a pointer to something they own (either directly or via view types like std::string_view or std::span), disabling the rvalue overloads can prevent errors:
struct foo {
int* take_ptr_bad() { return &x; }
int* take_ptr() & { return &x; }
int x;
};
foo get_foo();
void bar() {
auto ptr = get_foo().take_ptr_bad();
// ptr is dangling
auto ptr = get_foo().take_ptr();
// does not compile
}
The other is to provide some optimizations. For instance, you might overload a getter function to return an rvalue reference if this is an rvalue to prevent unnecessary copies:
struct foo {
const std::string& get_str() const & {
return s;
}
std::string&& get_str() && {
return std::move(s);
}
std::string s;
};
void sink(std::string);
foo get_foo();
void bar() {
sink(get_foo().get_str());
// moves the string only if the r-value overload is provided.
// otherwise a copy has to be made, even though the foo object
// and transitively the string is temporary.
}
These are how I use the feature, and I'm sure there are more use cases.
|
71,845,084 | 71,845,499 | Copy part of texture to another texture OpenGL 4.6 C++ | If I have to texture IDs
SrcID and DestID
How can i copy a part of srcID to DestId
Given the normalised coordinates of the part to be copied, width and height of both src and dest
By normailsed I mean they are between 0 and 1
| You can attach the textures to a framebuffer, and then use glBlitFramebuffer. I can't test the code below, but it should be about right. You only need to specify the coordinates in pixels, but it's easy to compute by multiplying normalized coordinates by texture dimensions.
GLuint FboID;
glGenFramebuffers(1, &FboID);
glBindFramebuffer(GL_FRAMEBUFFER, FboID);
// Attach the textures to atttachment slots
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, SrcID, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, DestID, 0);
// Prepare to read from first attachment (src texture)
// and draw into second attachment (dst texture)
glReadBuffer(GL_COLOR_ATTACHMENT0);
GLenum[] DstBuffer = { GL_COLOR_ATTACHMENT1 };
glDrawBuffers(1, &DstBuffer);
// Fill those pixel coordinates from your normalized coordinates
// (e.g. srcX0 = 0.2f * srcWidth)
GLint srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1;
glBlitFramebuffer(
srcX0, srcY0,
srcX1, srcY1,
dstX0, dstY0,
dstX1, dstY1
GL_COLOR_BUFFER_BIT,
GL_LINEAR);
glBindFramebuffer(GL_FRAMEBUFFER, 0); // disable FBO
// optionally delete FBO, if you won't need it anymore
// glDeleteFramebuffers(1, &FboID);
|
71,845,120 | 71,845,207 | Resource leak or false positive | I have a code like this:
std::string getInfo(FILE *fp)
{
char buffer[30];
if (fread(buffer, 19, 1, fp) == 1)
buffer[19] = '\0';
else
buffer[0] = '\0';
return buffer;
}
I'm using cppcheck for static analysis and it spits a warning:
error: Resource leak: fp [resourceLeak]
return buffer;
^
The way I see it, since the return is by value, the data will be copied from "buffer" into std::string's storage, so there's no leak there.
Does this pose some real problem or is it a false positive?
|
error: Resource leak: fp [resourceLeak]
You are not leaking any resource from this function. So, if you're only analyzing this function, this is a bug in your cppcheck. However, as @Taekahn points out - maybe the leak is elsewhere in your program.
Also, since you're returning std::string, you can use a constructor taking a pointer and a count, and not bother with the '\0' in the buffer:
std::string getInfo(FILE *fp)
{
static constexpr const std::size_t info_length { 19 };
char buffer[info_length];
if (fread(buffer, info_length, 1, fp) == 1)
return {buffer, info_length};
else
return {};
}
If you're using C++23, you might consider returning an std::expected instead of the empty string, e.g. something like:
std::expected<std::string, errc> getInfo(FILE *fp)
{
static constexpr const std::size_t info_length { 19 };
char buffer[info_length];
if (fread(buffer, info_length, 1, fp) == 1)
return std::string{buffer, info_length};
else
return std::unexpected{errno};
}
|
71,845,313 | 71,847,235 | Using GMP, omit mpz_clear() after mpz_roinit_n()? | The GMP library provides a big int C API and a C++ API which wraps the C API. Usually you initialize an mpz_t struct (C API) by doing
mpz_t integ;
mpz_init(integ);
(see 5.1 Initialization Functions). When doing so, you later have to free the memory with mpz_clear(integ);. The C++ API's mpz_class handles this deallocation automatically for you.
Now, if you want to initialize an mpz_t based on existing memory, and you don't want to copy the memory contents, you can use the function mpz_roinit_n() (5.16 Integer Special Functions) for a memory area pointed to by xp:
mpz_srcptr mpz_roinit_n(mpz_t x, const mp_limb_t *xp, mp_size_t xs)
This initializes x in a special way so it can be used as a read-only input operand (hence the ro in the function name) to other mpz functions. Now, the documentation of mpz_clear(integ) says this:
Free the space occupied by x. Call this function for all mpz_t
variables when you are done with them.
I wonder if mpz_t's which have been initialized with a call to mpz_roinit_n() are an exemption to this rule, because they don't need to be deallocated.
If I'm correct, this would also mean that mpz_roinit_n() can't be used with the C++ API's mpz_class, not even with mpz_class.get_mpz_t(), because mpz_class's destructor always tries to deallocate the underlying mpz_t, and this would cause memory issues. Am I correct here?
| mpz_clear does nothing on a mpz_t set with mpz_roinit_n. So you don't need to call it, but it is still safe if it gets called.
|
71,845,818 | 71,845,891 | MSVC vs GCC & Clang Bug while using lambdas | I was trying out an example presented at CppCon that uses lambdas. And to my surprise the program don't compile in gcc and clang(in either C++14 or C++17) but compiles in msvc. This can be verified here.
For reference, the example code is as follows:
#include <stdio.h>
int g = 10;
auto kitten = [=]() { return g+1; };
auto cat = [g=g]() { return g+1; };
int main() {
g = 20;
printf("%d %d\n", kitten(), cat());
}
What is the problem here(if any) and which compiler is right?
Note that the code is an exact copy-paste from their official presentation slide.
| This is a problem with MSVC. clang and g++ are correct.
From [expr.prim.lambda.capture]/3 (C++17 draft N4659)
A lambda-expression whose smallest enclosing scope is a block scope (6.3.3) is a local lambda expression; any
other lambda-expression shall not have a capture-default or simple-capture in its lambda-introducer. The
reaching scope of a local lambda expression is the set of enclosing scopes up to and including the innermost
enclosing function and its parameters. [ Note: This reaching scope includes any intervening lambda-expressions.
—end note ]
Since = is a capture-default, and the lambda is not within a block-scope, the code is not valid.
|
71,846,557 | 71,940,201 | Importing C++ library installed using vcpkg on mac? | My goal is to install a library (rbdl-orb) on my Mac and import the library in a C++ program.
My first attempt was to clone the library and run the included example directly. The program "example.cc" starts with the following two lines:
#include <iostream>
#include <rbdl/rbdl.h>
The CMake file follows:
PROJECT (RBDLEXAMPLE CXX)
CMAKE_MINIMUM_REQUIRED(VERSION 3.0)
# We need to add the project source path to the CMake module path so that
# the FindRBDL.cmake script can be found.
LIST( APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR} )
SET(CUSTOM_RBDL_PATH "" CACHE PATH "Path to specific RBDL Installation")
# Search for the RBDL include directory and library
FIND_PACKAGE (RBDL REQUIRED)
FIND_PACKAGE (Eigen3 3.0.0 REQUIRED)
# Add the include directory to the include paths
INCLUDE_DIRECTORIES ( ${RBDL_INCLUDE_DIR} ${EIGEN3_INCLUDE_DIR} )
# Create an executable
ADD_EXECUTABLE (example example.cc)
# And link the library against the executable
TARGET_LINK_LIBRARIES (example
${RBDL_LIBRARY}
)
Typing "make example" yields the following error:
c++ example.cc -o example
example.cc:10:10: fatal error: 'rbdl/rbdl.h' file not found
#include <rbdl/rbdl.h>
^~~~~~~~~~~~~
1 error generated.
make: *** [example] Error 1
I am guessing that there are steps needed to install the library, such that the C++ compiler knows where to look for the files when it sees the command "import". The library's GitHub notes that the package is available for installation through vcpkg.
I installed vcpkg by following the instructions. Then, I built the library by typing "vcpkg install rbdl" in a Terminal. Typing "vcpkg list" in the working directory shows that the library appears to be installed:
(base) my_name@my_name-MacBook-Pro current_directory % vcpkg list
eigen3:arm64-osx 3.4.0#2 C++ template library for linear algebra: matrice...
rbdl:arm64-osx 2.6.0#2 Rigid Body Dynamics Library
vcpkg-cmake-config:arm64-osx 2022-02-06
vcpkg-cmake:arm64-osx 2022-04-07
Unfortunately, typing "make example" again yields the following error:
c++ example.cc -o example
example.cc:10:10: fatal error: 'rbdl/rbdl.h' file not found
#include <rbdl/rbdl.h>
^~~~~~~~~~~~~
1 error generated.
make: *** [example] Error 1
The error suggests that the C++ compiler is not aware of the location where the library was installed.
How can I correctly install the library and import it in my C++ program?
| Reinstalled the library using "sudo" and started using the vcpkg installation and made the following change to the CMake file:
SET(CMAKE_CXX_STANDARD 11)
After these changes, the library is running correctly.
|
71,847,007 | 71,847,066 | Pointer to an array has it's elements freed once outside scope | I am trying to read from a binary file, and then convert the binary information from a char[] pointer to an int[] pointer.
I was wondering, is there something similar to static int var[], but for dynamically allocated arrays?
I am trying to find a way to tell C++ to not free up the memory after exiting the function.
imagein.open(loc, ios::binary);
//Creates a pointer to a list of chars with a length of 8, which is just enough for 2 ints
char* timechar = new char[8];
//Reads 8 bytes of data from the file
imagein.read(timechar, 8);
//Creates an int pointer with enough room for 2 vars
int* ints = new int[2];
//Tells C that everything within timechar is now an int, and copies the contents to the ints pointer
ints = (int*)timechar;
//gets the width, and height of the image from the 1st 2 bytes
width = ints[0];
height = ints[1];
//Creates the size var
size = width * height;
//sets the ammout of ints to read to the width * height
times = size;
//creates a pointer to a list of chars so that we can read the data from the file
char* chars = new char[times * 4];
//Reads the rest of the file into chars
imagein.read(chars,times*4);
//reinitilizes buffer to be the correct size to the compiler
int* temp= new int[size+2];
//shifts the pointer to the buffer over twice
++temp;
++temp;
//takes everything from chars and tells C that all the bits within the chars var are copied over as int's
temp = (int*)chars;
//Shifts the buffer pointer back to where it should be
--temp;
--temp;
//sets the 1st, and 2nd buffer vars to the width, and height of the given image
temp[0] = width;
temp[1] = height;
//increases size to the correct size of the array buffer
size += 2;
I want to get the temp[] of ints to persist after exiting the function.
I am new to C++, and I'm not sure of other ways to accomplish what I'm trying to do.
| Edit: This is most likely not what the OP needs, but it is what they asked, so I'll keep this answer around instead of deleting it in case anyone else lands here.
I am trying to find a way to tell C++ to not free up the memory after exiting the function.
The normal reason people want this is in to recycle the dynamically allocated memory across multiple invocations of the function. It "sometimes" has interesting performance benefits, at the cost of preventing the function from being used in multiple threads concurrently.
If that's not what you are attempting to do, then stop reading. Otherwise...
If you want to recycle temporary dynamic storage this way, then a static local variable will get you what you want.
Here's what it would look like using a std::vector<>, which you really should instead of raw array pointers.
void someFunction(std::size_t size) {
static vector<int> temp;
// ...
if(temp.size() < size+2) {
temp.resize(size+2);
}
}
|
71,847,035 | 71,847,085 | Operator precedence - increment versus member access | Consider this:
++iterator->some_value
Will the iterator be forwarded before some_value is accessed?
According to cppreference increment and member access both have the same precedence of 2. Does the order in which they are listed matter? Or is this undefined - compiler specific?
| Note that preincrement and postincrement have different precedences, so the code snippet you've posted doesn't quite match the explanatory text you've linked.
The preincrement operator has a lower precedence than the member access operator, so ++iterator->some_value is the equivalent of ++(iterator->some_value).
If instead you had iterator->some_value++ where they both had the same precedence, then the left-to-right associativity comes into effect, and it would be processed as (iterator->some_value)++.
|
71,847,341 | 71,847,384 | last character of a string in c++ using n.back() and casting | my input is 12. Why is the output 50?
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string n;
cin>>n;
cout << (int)n.back();
}
|
my input is 12. Why is the output 50?
Because the value that encodes the code unit '2' in the character encoding that is in use on your system happens to be 50.
If you wish to print the symbol that the code unit represents, then you must not cast to int type, and instead insert a character type:
std::cout << n.back();
If you wish to map a character representing '0'..'9' to the corresponding integer value, you can use character - '0'. Why this works: Regardless of what value is used to represent the digit '0', subtracting its own value from itself will produce the value 0 because z - z == 0. The other digits work because of the fact that all digits are represented by contiguous values starting with '0'. Hence, '1' will be represented by '0' + 1 and z + 1 - z == 1.
|
71,847,724 | 71,849,987 | How to write custom input function for Flex in C++ mode? | I have a game engine and a shader parser. The engine has an API for reading from a virtual file system. I would like to be able to load shaders through this API. I was thinking about implementing my own std::ifstream but I don't like it, my api is very simple and I don't want to do a lot of unnecessary work. I just need to be able to read N bytes from the VFS. I used a C++ mod for more convenience, but in the end I can not find a solution to this problem, since there is very little official information about this. Everything is there for the C API, at least I can call the scan_string function, I did not find such a function in the yyFlexParser interface.
To be honest, I wanted to abandon the std::ifstream in the parser, and return only the C api . The only thing I used the Flex C++ mode for is to interact with the Bison C++ API and so that the parser can be used in a multi-threaded environment, but this can also be achieved with the C API.
I just couldn't compile the C parser with the C++ compiler.
I would be happy if there is a way to add such functionality through some kind of macro.
I wouldn't mind if there was a way to return the yy_scan_string function, I could read the whole file myself and provide just a string.
| The simple solution, if you just want to provide a string input, is to make the string into a std::istringstream, which is a valid std::istream. The simplicity of this solution reduces the need for an equivalent to yy_scan_string.
On the other hand, if you have a data source you want to read from which is not derived from std::istream, you can easily create a lexical scanner which does whatever is necessary. Just subclass yyFlexLexer, add whatever private data members you will need and a constructor which initialises them, and override int LexerInput(char* buffer, size_t maxsize); to read at least one and no more than maxsize bytes into buffer, returning the number of characters read. (YY_INPUT also works in the C++ interface, but subclassing is more convenient precisely because it lets you maintain your own reader state.)
Notes:
If you decide to subclass and override LexerInput, you need to be aware that "interactive" mode is actually implemented in LexerInput. So if you want your lexer to have an interactive mode, you'll have to implement it in your override, too. In interactive mode, LexerInput always reads exactly one character (unless, of course, it's at the end of the file).
As you can see in the Flex code repository, a future version of Flex will use refactored versions of these functions, so you might need to be prepared to modify your code in the future, although Flex generally maintains backwards compatibility for a long time.
|
71,847,803 | 71,847,966 | How to iterate over a map and match its key values with enum class members? | I have a quick question.
Is there any trick to iterate through the keys of a map and use them to access an enumerate class items.
For example, lets say we have the Color class as defined below.
enum class Color {blue = 0, green = 1, yellow = 2};
unordered_map<string, string> mp {
{"blue",""},
{"green",""},
{"yellow",""},
{"red", ""}
};
for (auto e: mp) {
if(e.first.compare("blue") ==0) { // e.first == "blue"
e.second = fGetVal(Color::blue);
} else if (e.first.compare("green") ==0) {
e.second = fGetVal(Color::green);
} else if (e.first.compare("yellow") ==0) {
e.second = fGetVal(Color::yellow);
} else {
cout<<"the requested color is not supported!"
}
}
// assume fGetVal() takes the enum class type as input and returns it value as a string
Is there a better approach than using if/else-if to call method fGetVal?
More specifically trying to use a variable name for accessing enum class elements something like Color::e.first
| A clean way to do is is to pre-cache the results of fGetVal() in a map and just do a simple lookup:
const unordered_map<string, string> colorStringsMap = {
{"blue", fGetVal(Color::blue)},
{"green", fGetVal(Color::green)},
{"yellow", fGetVal(Color::yellow)},
};
int main() {
unordered_map<string, string> mp {
{"blue",""},
{"green",""},
{"yellow",""},
{"red", ""}
};
for (auto& e: mp) {
try {
e.second = colorStringsMap.at(e.first);
}
catch(std::out_of_range) {
cout <<"the requested color is not supported!";
}
}
}
|
71,847,915 | 71,848,466 | C++ overloading '+' operator to get sum of data from 2 different linked lists | I am asked to overload operator '+' into the list class. I want the sum of all cgpa points of students from 2 different linked lists but don't know how to do it.
#include <iostream>
#include <cstring>
#include<algorithm>
using namespace std;
class StudentGroup
{
public:
struct Node
{
char* name;
double cgpa;
Node* next;
};
Node* head = 0;
public:
StudentGroup()
{
head = nullptr;
}
StudentGroup(const StudentGroup &list);
~StudentGroup();
bool insert(char* name, double cgpa);
bool removeNode(char* name);
void print();
double& cumulativeGPA(char* name);
};
above code is what I've done for class definition.
bool StudentGroup::insert(char* name, double cgpa)
{
bool Insert = false;
Node* temp;
Node* newnode = new Node();
newnode->name = new char[strlen(name)+1];
strcpy(newnode->name,name);
newnode->cgpa = cgpa;
newnode->next = 0;
if (head == 0)
{
head = temp = newnode;
}
else
{
temp->next = newnode;
temp = newnode;
}
Insert = true;
return Insert;
}
and here is the code I wrote to create lists and add objects to them.
int main()
{
StudentGroup list1, list3, list4;
list3.insert("Michael Faraday", 4.2);
list3.insert("Marie Curie", 3.8);
list4.insert("Albert Einstein", 4.2);
list4.insert("Alan Turing", 3.8);
//Copy constructor
StudentGroup list2=list1;
list1.~StudentGroup();
list2.print();
list1.print();
//Operator overloading
list3.print();
list4.print();
list3 = list4;
}
and above is the main function. What I need is something like:
list3+list4//code
16//output
How to do that? Sorry if my question doesn't fit the usual format, complete beginner here and due to limited time I had to ask.
| It's as simple as looping through both lists/groups and adding up their cpga:
// put inside class declaration
double operator+(const StudentGroup& student2);
// function definition
double StudentGroup::operator+(const StudentGroup& student2)
{
double ret = 0.0;
Node* pStudent;
for (pStudent = this->head; pStudent; pStudent = pStudent->next)
ret += pStudent->cgpa;
for (pStudent = student2.head; pStudent; pStudent = pStudent->next)
ret += pStudent->cgpa;
return ret;
}
|
71,848,371 | 71,849,380 | Deep copying a vector of pointers in derived class | I have a pure virtual class called Cipher
class Cipher
{
public:
//This class doesn't have any data elements
virtual Cipher* clone() const = 0;
virtual ~Cipher() { };
//The class has other functions as well, but they are not relevant to the question
};
Cipher has a few other derived classes (for example CaesarCipher). The question will be about CipherQueue, which looks something like this:
//I've tried to only include the relevant parts here as well
class CipherQueue: public Cipher
{
std::vector<Cipher*> tarolo;
public:
void add(Cipher* cipher)
{tarolo.push_back(cipher);}
CipherQueue(const CipherQueue& _rhs); //?????
CipherQueue* clone() const; //?????
~CipherQueue()
{
for (size_t i = 0; i < tarolo.size(); i++)
{
delete tarolo[i];
}
//tarolo.clear(); //not sure if this is needed
}
CipherQueue has a vector called tarolo. It contains pointers to the derived classes of Cipher. You can add elements to this vector by using the new operator, or the clone function (which has already been implemented) of the given class:
CipherQueue example;
example.add(new CaesarCipher(3))
CaesarCipher c(6);
example.add(c.clone());
//It is the job of the CipherQueue class to free up the memory afterwards in both cases
Now the question is: how can I implement the copy constructor and the clone function in CipherQueue, so that the copy constructor is used in the clone function, and the clone function creates a deep copy of the object that it is called on?
I've already made what I think is a shallow copy, which isn't good, because the destructor, ~CipherQueue() doesn't work with a shallow copy. (Or could the destructor be wrong as well?)
The goal is to make it so that you can do something like this:
CipherQueue example;
CipherQueue inside; //Let's say that this already has a few elements in it
example.add(inside.clone());
example.add(example.clone()); //This should also work
Here's what I've tried before, without using the copy constructor (which is a shallow copy I think, and therefore it causes my program to get a segmentation fault):
CipherQueue* clone() const
{
CipherQueue* to_clone = new CipherQueue;
to_clone->tarolo = this->tarolo;
return to_clone;
}
| Thank you Marius Bancila, you are right, the problem was that I was just copying the pointers, and not creating new objects in the new vector. I called clone() on each object, and now it works perfectly! Here is the working clone function, in case anyone stumbles upon this thread in the future:
CipherQueue* clone() const
{
CipherQueue* to_clone = new CipherQueue;
to_clone->tarolo = this->tarolo; //First we copy the pointers
for (size_t i = 0; i < this->tarolo.size(); i++)
{
to_clone->tarolo[i] = tarolo[i]->clone(); //Then we use the clone function on each element to actually create new objects, and not just have copied pointers
}
return to_clone;
}
In the end, it seems like I didn't need the copy constructor at all. You can make the clone function without it.
|
71,848,820 | 71,849,107 | Understand std::map::insert & emplace with hint | map insert comparison
Question> I try to understand the usage of insert & emplace with hint introduced to std::map. During the following test, it seems to me that the old fashion insert is fastest.
Did I do something wrong here?
Thank you
static void MapEmplaceWithHint(benchmark::State& state) {
std::vector<int> v{12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
std::map<int, int> mapInt;
auto where(std::end(mapInt));
for (auto _ : state) {
for (const auto &n : v) { // Items in non-incremental order
where = mapInt.emplace_hint(where, n, n+1);
}
}
}
BENCHMARK(MapEmplaceWithHint);
static void MapInsertWithHint(benchmark::State& state) {
std::vector<int> v{12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
std::map<int, int> mapInt;
auto where(std::end(mapInt));
for (auto _ : state) {
for (const auto &n : v) { // Items in non-incremental order
where = mapInt.insert(where, {n, n+1});
}
}
}
BENCHMARK(MapInsertWithHint);
static void MapInsertNoHint(benchmark::State& state) {
std::vector<int> v{12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
std::map<int, int> mapInt;
for (auto _ : state) {
for (const auto &n : v) { // Items in non-incremental order
mapInt.insert({n, n+1});
}
}
}
BENCHMARK(MapInsertNoHint);
static void MapReverseInsertNoHint(benchmark::State& state) {
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12};
std::map<int, int> mapInt;
for (auto _ : state) {
for (const auto &n : v) { // Items in incremental order
mapInt.insert({n, n+1});
}
}
}
BENCHMARK(MapReverseInsertNoHint);
static void MapEmplaceNoHint(benchmark::State& state) {
std::vector<int> v{12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
std::map<int, int> mapInt;
for (auto _ : state) {
for (const auto &n : v) { // Items in non-incremental order
mapInt.emplace(n, n+1);
}
}
}
BENCHMARK(MapEmplaceNoHint);
| First, let's create a dataset more meaningful than 12 integers:
std::vector<int> v(10000);
std::iota(v.rbegin(), v.rend(), 0);
Results from all functions are now more comparable: https://quick-bench.com/q/HW3eYL1RaFMCJvDdGLBJwEbDLdg
However, there's a worse thing. Notice that looping over state makes it perform the same operations several times to measure the average time. But, since you are reusing the same map, each insert or emplace after the first loop iteration is failing, so you mostly measure time of failed inserts, where hint doesn't help.
Test cases should look more like this:
std::vector<int> v(1000);
std::iota(v.rbegin(), v.rend(), 0);
for (auto _ : state) {
std::map<int, int> mapInt;
auto where(std::end(mapInt));
for (const auto &n : v) { // Items in non-incremental order
where = mapInt.emplace_hint(where, n, n+1);
}
}
And with this, hints start to shine (had to limit data to 1000, otherwise I'd get timeouts): https://quick-bench.com/q/2cR4zU_FZ5HQ6owPj9Ka_y9FtZE
I'm not sure if the benchmarks are correct, but quick glance in the assembly suggests that inserts were not optimized altogether, so there's a chance it's good enough.
As noticed by Ted Lyngmo, try_emplace() with hint tends to perform (slightly) better:
https://quick-bench.com/q/evwcw4ovP20qJzfsyl6M-_37HzI
|
71,848,888 | 71,850,806 | Generated window with GLFW, background color not changing | I'm trying to change the background color in a window generated by OpenGL/GLFW and I'm using a similar code than the one in the GLFW docs. I'm on Ubuntu 20.04 and the window background is always black, no matter the parameters in the glClearColor() function.
I tried this on Windows 10 using VS and it worked perfectly, but on Ubuntu it's not working at all. No error messages are generated.
I also followed The Cherno's Sparky game engine series, and tried encapsulating the glClear() function in a class method, but this didn't change anything.
This is the whole code:
#include <iostream>
#include <GL/gl.h>
#include <GLFW/glfw3.h>
int main(int argc, char *argv[])
{
std::cout << "Hello world!" << std::endl;
if (!glfwInit())
{
// Initialization failed
exit(EXIT_FAILURE);
}
GLFWwindow* window = glfwCreateWindow(640, 480, "My Title", NULL, NULL);
if (!window)
{
// Window or OpenGL context creation failed
std::cout << "Error creating window!" << std::endl;
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
return 0;
}
I'm supposed to get a window with a red background but it's black.
As additional elements, I'm also using CMake to help configuring and building the project (quite overkill I know), and I believe clang is the compiler used for the project. Maybe that influences the result.
| You need an appropriate loader after glfwMakeContextCurrent(window).
If you are using glad, you should call gladLoadGL(glfwGetProcAddress) after glfwMakeContextCurrent(window) as the official doc suggests here.
|
71,849,467 | 71,851,038 | C++ proto2 nested message has field checks | In C++ proto2 is it required to do a has_ check before trying to access nested proto message fields?
message Foo {
optional Bar1 bar_one = 1;
}
message Bar1 {
optional Bar2 bar_two = 2;
}
message Bar2 {
optional int value = 3;
}
Foo foo;
if (!foo.has_bar_one() || !foo.bar_one().has_bar_two() || !foo.bar_one().bar_two().has_value()) {
// No value
}
or is it fine to just do:
if (!foo.bar_one().bar_two().has_value()) {
// No value
}
| After checking the generated code, it seems your second approach will do just fine. The generated code for bar_one is:
inline const ::Bar1& Foo::_internal_bar_one() const {
const ::Bar1* p = bar_one_;
return p != nullptr ? *p : reinterpret_cast<const ::Bar1&>(
::_Bar1_default_instance_);
}
inline const ::Bar1& Foo::bar_one() const {
// @@protoc_insertion_point(field_get:Foo.bar_one)
return _internal_bar_one();
}
and basically what this is doing is that, it will provide the object if it is set, and it will provide a default instance if its not. This will do the same for bar_two and for value.
So in the end if you check has_value, and its true, it means all the above objects are set, and if its false, at least value is not set. So if you just care about value, your second check will do just fine.
|
71,849,786 | 72,738,589 | glXSwapBuffers glitchy timing | I have been getting very glitchy timings in my render loop causing rendering to stutter. I have set up timing around my glXSwapBuffers call like so:
Timer timer;
glXSwapBuffers(display, window);
timer();
if (timer.elapsed_seconds > 0.1)
printf("stutter(%f)\n\r", timer.elapsed_seconds);
And am getting results like:
stutter(0.109081)
stutter(0.108956)
stutter(0.662115)
stutter(0.759556)
stutter(0.657789)
stutter(0.283185)
stutter(0.105581)
stutter(0.106285)
stutter(0.572289)
stutter(0.199908)
stutter(0.218540)
stutter(0.752033)
stutter(0.148225)
What could be causing glXSwapBuffers to take so long to call? How can I fix the stuttering?
| After much testing and debugging I found that my Timer class was computing the difference between two timestamps wrong. The tv_nsec component was being incorrectly divided causing elapsedSeconds to return varying results.
After correcting this the stuttering went away immediately.
|
71,849,922 | 71,850,184 | c++ map insert fails to compile when inserting an object that contains a unique_ptr | I am having trouble (compile time, gcc 17) inserting an object in an std::map which contains a unique_ptr. If I use a regular pointer it compiles (if I take the copy constructor out!).
Here is the struct containing a unique_ptr. With a ctor, copy ctor, etc, with std::move semantics everywhere. Has anyone seen this issue before?
#include <utility> // std::pair, std::make_pair
#include <string> // std::string
#include <iostream> // std::cout
#include <map>
#include <memory>
struct Struct1
{
Struct1(std::unique_ptr<std::string> pStr)
: pStr_(std::move(pStr)){}
~Struct1(){}
Struct1(Struct1& other)
: pStr_(std::move(other.pStr_)){}
std::unique_ptr<std::string> pStr_;
};
Here is the main. Anything I try I get a "no matching function" for insert
int main () {
std::string s("key");
std::unique_ptr<std::string> pStr = std::make_unique<std::string>("Hello");
std::map<std::string, Struct1>list;
Struct1 ste(std::move(pStr));
std::pair<std::string, Struct1> p(s,ste); // copy into a pair
// std::pair<std::string, Struct1> p(s,std::move(ste)); // copy into a pair
// auto p = std::make_pair(s, std::move(ste));
// auto p = std::make_pair(s, ste);
// list.insert(std::move(p));
list.insert(p);
| Struct1(Struct1& other)
As per language standard, it's the copy constructor; what you did here (by typo or on purpose, I don't know) is a auto_ptr-style neither-move-nor-copy-semantics. Though with that done, the copy assignment is auto-generated, while the move operations are completely removed (unless defined manually).
Didn't you want that instead?
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <memory>
struct Struct1
{
Struct1(std::unique_ptr<std::string> pStr)
: pStr_(std::move(pStr)){}
~Struct1(){}
Struct1(Struct1&& other) //double! ampersand
: pStr_(std::move(other.pStr_)){}
std::unique_ptr<std::string> pStr_;
};
int main () {
std::string s("key");
std::unique_ptr<std::string> pStr = std::make_unique<std::string>("Hello");
std::map<std::string, Struct1>list;
Struct1 ste(std::move(pStr));
std::pair<std::string, Struct1> p{s,std::move(ste)}; //note the move
list.insert(std::move(p)); //and here
}
https://godbolt.org/z/fs44j69ja
|
71,850,472 | 71,850,736 | Return an error for two inputs of numbers if not an integer | I am trying to make the program return an error if the user input characters/strings to num1, num2 and then take a right input instead
I searched the internet and found the solution with cin.fail() but it works only for the first number or doesn't work at all
I was advised to do it by figuring out the type of variable and then compare but I cant figure it out
How can I make validation in easiest simplest way possible without functions but loops?
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int num1, num2; // two integers
int choice; // chosen integers
int ch1 = 0, ch2 = 0,ch3 = 0,ch4 = 0,ch5 = 0; // to keep track of chosen functions
//const for choice of menu
const int addition = 1,
substruction = 2,
multiplication = 3,
division = 4,
modulo = 5,
numberChange = 6;
//intro
cout << "This program has been made for arithmetic operations.\n";
cout << "Please choose two integers for arithmetic operations\n";
cin >> num1 >> num2;
do {
cout << "Choose number of the operation you want to do\n";
cout << "1. addition\n";
cout << "2. subtraction\n";
cout << "3. multiplication\n";
cout << "4. division\n";
cout << "5. modulo\n";
cout << "6. CHANGE OF NUMBERS\n";
cout << "To exit menu enter -1!\n";
cin >> choice;
switch (choice) {
case 1:
cout << "Result: " <<num1 << " + " << num2 << " = "<< num1 + num2 << endl;
ch1++;
break;
case 2:
cout << "Result: " <<num1 << " - " << num2 << " = "<< num1 - num2 << endl;
ch2++;
break;
case 3:
cout << "Result: " <<num1 << " * " << num2 << " = "<<num1 * num2 << endl;
ch3++;
break;
case 4:
cout << "Result: " <<num1 << " / " << num2 << " = "<<num1 / num2 << endl;
ch4++;
break;
case 5:
cout << "Result: " <<num1 << " % " << num2 << " = "<<num1 % num2 << endl;
ch5++;
break;
case 6:
cout << "Okay, you can choose different numbers" << endl;
cin >> num1 >> num2;
break;
case -1:
ofstream myfile ("/Users/margaritakholostova/Desktop/us.txt");
if (myfile.is_open())
{
myfile << "Addition was selected " << ch1 << " times\n";
myfile << "Subtraction was selected " << ch2 << " times\n";
myfile << "Multiplication was selected " << ch3 << " times\n";
myfile << "Division was selected " << ch4 << " times\n";
myfile << "Modulo was selected " << ch5 << " times\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
break;
}
//return error if input is not integer
if (cin.fail()) {
cout << "Error! Please put only integers!" << endl;
cin.clear();
cin.ignore(256, '\n');
cin >> choice;
}
// validate the input for right number
while (choice < addition || choice > numberChange )
{
if (choice != -1) {
cout << "Please choose valid option out of menu (1-5)\n";
cin >> choice;
}
}
} while (choice != -1);
}
| You need to check the error state of std::cin before you act on the value returned by operator>>. Try something more like this instead:
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
int main () {
int num1, num2; // two integers
int choice; // chosen integers
int ch1 = 0, ch2 = 0, ch3 = 0, ch4 = 0, ch5 = 0; // to keep track of chosen functions
//const for choice of menu
const int addition = 1,
substruction = 2,
multiplication = 3,
division = 4,
modulo = 5,
numberChange = 6;
//intro
cout << "This program has been made for arithmetic operations.\n";
cout << "Please choose two integers for arithmetic operations\n";
//return error if input is not integers
while (!(cin >> num1 >> num2)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Error! Please enter only integers!\n";
}
do {
cout << "Choose number of the operation you want to do\n";
cout << "1. addition\n";
cout << "2. subtraction\n";
cout << "3. multiplication\n";
cout << "4. division\n";
cout << "5. modulo\n";
cout << "6. CHANGE OF NUMBERS\n";
cout << "To exit menu enter -1!\n";
//return error if input is not integer
while (!(cin >> choice)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Error! Please enter only integers!\n";
}
// validate the input for right number
switch (choice) {
case 1:
cout << "Result: " << num1 << " + " << num2 << " = " << num1 + num2 << '\n';
ch1++;
break;
case 2:
cout << "Result: " << num1 << " - " << num2 << " = " << num1 - num2 << '\n';
ch2++;
break;
case 3:
cout << "Result: " << num1 << " * " << num2 << " = " << num1 * num2 << '\n';
ch3++;
break;
case 4:
cout << "Result: " << num1 << " / " << num2 << " = " << num1 / num2 << '\n';
ch4++;
break;
case 5:
cout << "Result: " << num1 << " % " << num2 << " = " << num1 % num2 << '\n';
ch5++;
break;
case 6:
cout << "Okay, you can choose different numbers\n";
while (!(cin >> num1 >> num2)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Error! Please enter only integers!\n";
}
break;
case -1: {
ofstream myfile ("/Users/margaritakholostova/Desktop/us.txt");
if (myfile.is_open()) {
myfile << "Addition was selected " << ch1 << " times\n";
myfile << "Subtraction was selected " << ch2 << " times\n";
myfile << "Multiplication was selected " << ch3 << " times\n";
myfile << "Division was selected " << ch4 << " times\n";
myfile << "Modulo was selected " << ch5 << " times\n";
myfile.close();
}
else
cout << "Unable to open file\n";
return 0;
}
default:
cout << "Please choose a valid option from the menu (1-5)\n";
break;
}
}
while (true);
}
|
71,851,235 | 71,851,359 | How can I convert Python3 code to C++/Assembly language? | I want to convert a simple print(“Hello, World!”) code into the assembly language. I read a post, which showed that you can try to convert it to C++, and then to assembly, but that doesn’t work. Can someone help me covert Python3 to Assembly language(or to C++)?
| Here is a Stackoverflow thread that asks a similar questions (at least how to get Python to C) and has a few links to different projects that should do just that: Writing code translator from Python to C?
Also here is another project called PyPy that seems to be a replacement and faster version of CPython mentioned in the thread linked above: https://www.pypy.org/index.html
Hopefully one of these can help you out with what you're trying to do. In general though, if you need something compiled to Assembly Code you would be best off to just write it in C. The problem with Python is that it compiles to bytecode which is then ran by an interpreter. So at no point is it assembly. C however is compiled directly to assembly so it would give you exactly what you want. By trying to go from Python to assembly you're just adding an extra middle man (which is one of these projects I've linked) that has a potential to mess up, have a bug, etc. All that being said, hopefully one of these options is able to work out for you and get the jobs done! Have a great one and good luck!
|
71,851,305 | 71,851,619 | Construct cv::Mat via C++ 1D array | I took over a program, which use 1d array to construct cv::Mat. I'm confuse about it, and I make a demo:
int main()
{
short data[] = {
11, 12, 13, 14,
21, 22, 23, 24,
31, 32, 33, 34,
43, 42, 43, 44
};
cv::Mat m{ 4, 4, CV_8U, data};
cv::imwrite("test.png", m);
return 0;
}
I expect the output is
11 12 13 14
21 22 23 24
31 32 33 34
43 42 43 44
But I open the img in MATLAB:
11 0 12 0
13 0 14 0
21 0 22 0
23 0 24 0
| The 3rd parameter in the constructor you used for cv::Mat (CV_8U) specifies the format of the data buffer.
Your data is an array of short, i.e. each entry is 2 bytes. When you use values small values like you did, it means one of the bytes for each short will be 0.
When you use this buffer to initialized a cv::Mat of type CV_8U you tell opencv to treat the buffer as containing unsigned chars (1 byte elements). So each short is interpreted as 2 unsigned char bytes.
This is why you get the zeroes in the output.
Eaither change the type of the data buffer to unsigned char [], or change the cv::Mat data type to e.g. CV_16S. The 2 should usually match.
You can do it e.g. like this:
unsigned char data[] = {
11, 12, 13, 14,
21, 22, 23, 24,
31, 32, 33, 34,
43, 42, 43, 44
};
cv::Mat m{ 4, 4, CV_8U, data };
You can see the list of opencv data types here (in the Data types section):
https://docs.opencv.org/3.4/d1/d1b/group__core__hal__interface.html
|
71,851,356 | 71,851,470 | How to initialize a static array in C++ | Given the following very basic function, how would I initialize arr to all random values, and how would I initialize arr to a set of given values, say the numbers 0-11?
void func() {
static int arr[2][2][3];
}
With my limited knowledge of static variables and C++ in general, I think that the static array needs to be initialized in one line, so when the function is called again, it does not get re-initialized. Basically, I want to say:
static int arr[2][2][3] = another_array
But this raises an error that 'another_array' is not an initializer list. I looked up initializer lists but they all included classes and other stuff I didn't understand. Is there any way to initialize this array? Any help is appreciated.
| Technically if you try to assign the value of arr in a separate line, it will never be re-initialzied after the first time it was initialized. It will be re-assigned. But based on what you described, I assume that's the behavior you want to prevent.
So to initialized arr in the same line, what you could do is first create a function that will generate the desired number for you, then call that function many times during initializing arr:
int gen_num() {
// some code to return a random number for you...
}
void func() {
// I reduced `arr` to a 2D array, to make the code shorter. Making it a 3D array basically works the same
static int arr[2][3] = {{gen_num(), gen_num(), gen_num()}, {gen_num(), gen_num(), gen_num()}};
}
Note, if you make arr an std::array instead of the C-style array, then you can actually build up an array in a separate function, then just return the new array from that function:
std::array<std::array<int, 3>, 2> create_array()
{
std::array<std::array<int, 3>, 2> result;
// here you can assign each value separately
result[0][0] = 20;
result[2][1] = 10;
// or use for loop freely as needed
for(auto& arr : result)
{
for(auto& value : arr)
{
value = get_num();
}
}
return result;
}
void func() {
// Basically the same as having `int arr[2][3]`
static std::array<std::array<int, 3>, 2> arr = create_array();
}
|
71,851,439 | 71,851,579 | C++ rvalue shared_ptr and rvalue weak_ptr | std::shared_ptr<std::string> test() {
return std::make_shared<std::string>("sdsd");
}
cout << *test() << endl;
The above code works. Can someone please let me know where is the "sdsd" string stored. I was expecting it to error out as rvalue is a temporary object. Where is the rvalue copied to and stored in?
With weak_ptr
std::weak_ptr<std::string> test() {
return std::make_shared<std::string>("sdsd");
}
cout << *test().lock() << endl;
Interestingly the above code errors out. What's the difference?
| In
std::shared_ptr<std::string> test() {
return std::make_shared<std::string>("sdsd");
}
the constructed shared_ptr is returned and lives on as a temporary variable long enough to be used by the caller before going out of scope and freeing the string allocated by make_shared.
The "sdsd" string is stored in dynamic storage owned by the returned shared_ptr.
In
std::weak_ptr<std::string> test() {
return std::make_shared<std::string>("sdsd");
}
the shared_ptr wasn't returned and went out of scope, taking the string allocated by make_shared with it. Since this was the only existing copy of the shared_ptr this leaves the returned temporary weak_ptr variable connected to an expired share_ptr. If you test the return value of lock you'll see it's a default-constructed shared_ptr holding a null pointer.
Documentation for std::weak_ptr::lock.
The "sdsd" string isn't stored anywhere after test returns. It departed when the shared_ptr that owned it went out of scope.
|
71,851,994 | 71,852,063 | Private Struct only returnable with private listed first in a class | So I have run into the case where returning an object of type Node is not allowed if the private variables have been listed after the public as can be seen by the two screenshots below. There CLion is giving me an error as can be seen with Node being red. I understand why this is, however I am wondering if there is anyway to fix this issue without placing/declaring private before public?
Public before private (Desired):
Private before public (what works):
Thanks!
| The problem is that when the return type Node* is encountered in the member function getCurrentPalyer definition, the compiler doesn't know that there is a struct named Node. So you've to tell that to the compiler which you can do by adding a forward declaration for Node as shown below:
class Palyer
{ private: struct Node; //forward declaration added for Node
public:
Node* func()
{
return head;
}
private:
struct Node {};
Node* head;
};
Working Demo
|
71,852,071 | 71,852,350 | How to create a "factory function" for a templated class? | How would someone go about implementing a factory function for a templated class? Either my google searches aren't looking for the right thing, or I am misunderstanding the results. As an example:
template<typename T>
class Test
{
public:
T data;
void SizeOfData() { std::cout << "Data Size:" << sizeof(data) << "\n"; }
};
----this what I am trying to figure out how to do------
template <typename T>
Test<T> FactoryFunction(const std::string& type)
{
if(type == "int")
return Test<int>;
if(type == "long")
return Test<long long>;
}
----------------------------------------
int main()
{
auto a = FactoryFunction(std::string("int"));
auto b = FactoryFunction(std::string("long"));
a.SizeOfData();
b.SizeOfData();
a.data = 1;
b.data = 2;
}
Obviously, this code is all wrong - I am just trying to show what I want to do in theory. Can it be done? What do I look up in google - Factory functions to return templated classes? I am not even sure where to start. If someone could even point me in a direction - I really just want a function the returns the correct template instantiation based on the results of a switch or if/else list. I think conceptually the idea isn't hard, but implementing it is another thing - or I am really missing something.
Thanks for any help.
| The type T of a templated function has to be determined in compile time.
Therefore you cannot do it the way you mentioned.
However - you can use the following pattern to achieve a similar result:
#include <assert.h>
class TestBase
{
public:
virtual void SizeOfData() = 0;
};
template<typename T>
class Test : public TestBase
{
public:
T data;
virtual void SizeOfData() override { std::cout << "Data Size:" << sizeof(data) << "\n"; }
};
std::unique_ptr<TestBase> FactoryFunction(const std::string& type)
{
if (type == "int")
return std::make_unique<Test<int>>();
if (type == "long")
return std::make_unique<Test<long long>>();
return nullptr;
}
int main()
{
auto a = FactoryFunction(std::string("int"));
assert(a);
auto b = FactoryFunction(std::string("long"));
assert(b);
a->SizeOfData();
b->SizeOfData();
return 0;
}
Some notes:
Each instance of Test (where T changes) is a differnt an unrelated class. In order to create a connection between them, I added a common base class.
In order to use polymorphism, you must use refernce semantics. Therefore the factory returns a pointer (in this case a std::unique_ptr).
The common method you need to invoke on all your Test objects (SizeOfData) became a virtual method in the base class.
This technique is actually related to the idiom of type erasure mentioned in the comments.
UPDATE: based on the comment below, I replaced using naked news with std::make_unique.
You can see more info why it is better here: Differences between std::make_unique and std::unique_ptr with new
|
71,852,819 | 74,590,280 | Multiple audio tracks for video playback in Qt | I'm developing a small video editor to make quick edits to a multiple audio track video, using Qt. I'm a bit confused about whether it is possible or not to handle multiple audio tracks in payback and processing in Qt.
What I want to do with the video
list audio tracks
for each track, manage its volume, and choose to perform channel duplication on a mono track (to make it stereo).
play the video with the setting I chose for audio tracks, eventually being able to change settings on the fly.
extract a part of the video with the settings I chose.
I'm not sure if Qt can handle this by itself, or if I need to rely on a library specialized in video processing. Therefore, my question is double
If it is possible in Qt-only : how ?
I suppose I need to use QMediaPlayer class, but it doesn't look like it can handle multiple tracks at once.
Maybe by splitting the media into several sub-media, but then how to synchronize their playback?
Otherwise : external library. Are there any caveats to avoid?
I wonder what is the best way, if there is one, to display video frames (assuming audio will be handled by external lib)?
Should I draw frames directly on a QWidget, or should I use OpenGL directly? Or another method?
Note: I'm not forcibly looking for a detailed answer, I'm fine with short ones and/or external resources.
| After a bit of searching around, I found that it is impossible to do in with Qt as for now.
I found several libraries able to fulfill such purpose (list is non exhaustive for sure) :
libvlc, which was able to render easily on a QWidget surface, but at the time I looked, was not able to play multiple channels at a time. Next version should be able to do it tho.
libffmpeg and libav, which are a bit too low-level for what I want, and which I found fairly complicated to use to render on a QWidget surface.
libopenshot, which has quite a difficult learning curve, and not that much documentation unfortunately, as it is oriented toward nonlinear video editing.
libgstreamer. The one I chose.
I found libgstreamer to be the best for my purpose, being fairly high level, and well documented. It also is flexible to use, as it allows loading from and dumping to any kind of file automatically.
It is able to render directly on a QWidget surface, which is super convenient.
On the other hand, it has an async and dynamic design which requires a bit more planning and error management, but documentation is there to help.
So far I didn't encountered any major problem so far, I'll update this post if something new comes up.
|
71,853,780 | 71,854,590 | How to read data in a specific memory address in c++ | I have created an integer variable using the following code in first.cpp:
#include <iostream>
using namespace std;
int main()
{
int myvar = 10;
cout << &myvar;
// I only need two steps above.
// The following steps are coded to make this program run continuously.
cout << "Enter your name" << endl;
string name;
cin >> name;
return 0;
}
Output of first.cpp is:
>0x6dfed4
While the above program is running, I also run the following program in second.cpp:
#include <iostream>
using namespace std;
int main()
{
// I this program I want to read the content in myvar variable in first.cpp
// How to do it ?
}
Using the second program, I want to read the content of the myvar variable in first.cpp.
How to do it ?
Thank you.
| To elaborate on my comment above:
As I wrote each program will run in a different process.
Each process has a separate adddress space.
Therefore using the address of a variable in another process doesn't make any sense.
In order to communicate between processes, you need some kind of IPC (inter-process communication):
Inter-process communication
If you only need to share a variable, the first mechanism that comes to mind is to use shared memory:
Shared memory
Shared-memory is very much OS dependent.
You didn't mention which OS you are using.
On Windows you can use Win API for managing shared memory:
Windows shared memory
There's an equivalent on Linux, but I am not familiar with the details.
Alternatively you can use the boost solution which is cross platform:
boost shared memory
If you'll delve into that it will be clear that these kind of solutions comes with some compilcations.
So the question is why do you need to do it ? Maybe there's a better solution to your problem
(you haven't described what it actually is, so there's not much more I can say).
|
71,854,883 | 71,855,004 | Pointer to temporary object | Why does this code work correctly?
struct A {
std::string value = "test"s;
A() { std::cout << "created" << std::endl; }
~A() { std::cout << "destroyed" << std::endl; }
};
int main() {
A* ptr = nullptr;
{
A a;
ptr = &a;
}
std::cout << ptr->value << endl; // "test"
}
output:
created
destroyed
test
Or this example:
struct A {
const std::string* str = nullptr;
A(const std::string& s) : str(&s) {}
};
int main()
{
A a = std::string("hello world");
std::cout << *a.str;
return 0;
}
output:
hello world
In the first case, it seemed to me that when object A was destroyed, the content would become invalid, but I was able to retrieve the string.
In the second case, I took rvalue by constant reference, but extending the life of the object should work as long as the reference is valid. I thought that after the constructor worked, the string should have been destroyed. Why is this not happening?
| Both codes have undefined behavior.
Here:
{
A a;
ptr = &a;
}
std::cout << ptr->value << endl; // "test"
ptr becomes invalid once a goes out of scope and gets destroyed.
Similar in the second example, you are also dereferencing an invalid pointer because the temporary string is gone after the call to the constructor.
C++ does not define what happes when you do things that are not defined (makes sense, no? ;). Instead it is rather explicit about saying that when you do certain wrong things then the behavior of the code is undefined. Dereferencing an invalid pointer is undefined. The output of the code could be anything. A compiler is not required to diagnose undefined behavior, though there are features and tools that can help. With gcc it is -fsanitize=address that detects the issue in both your codes: https://godbolt.org/z/osc9ah1jo and https://godbolt.org/z/334qaKzb9.
|
71,854,988 | 71,858,066 | How to iterate in-macro integer value in a variable-parameter-length C++ macro (... and VA_ARGS)? | I am trying to write a C++ macro which would substitue a frequently-needed verbose code like
switch (id) {
case 0:
s << myFloat;
break;
case 1:
s << myInt;
break;
default: break;
}
with something like DESERIALIZE_MEMBERS(myFloat, myInt). s and id will not change names for the use case, so they don't need to be macro parameters.
It should support variable argument length, so DESERIALIZE_MEMBERS(myString, myArrayOfInts, myLong) for another case should also work, adding a third case statement to the switch expression.
However, it's not clear to me how to iterate the N value in case N: inside the macro for each argument.
Is that possible at all in standard C++ macros?
| In c++17, here is a solution.
First a compile-time constant type and value:
template<auto X>
using constant_t = std::integral_constant<decltype(X), X>;
template<auto X>
constexpr constant_t<X> constant_v;
Next, a variant over such constants:
template<auto...Is>
using enum_t = std::variant<constant_t<Is>...>;
this lets you generate a compile-time enumeration value at runtime and use it.
Now some code that lets you convert a runtime integer into a compile-time enumeration value:
template<std::size_t...Is>
constexpr enum_t<Is...> get_enum_v( std::index_sequence<Is...>, std::size_t i ) {
using generator = enum_t<Is...>(*)();
constexpr generator generators[] = {
+[]()->enum_t<Is...> {
return constant_v<Is>;
}...
};
return generators[i]();
}
template<std::size_t N>
auto get_enum_v( std::size_t i ) {
return get_enum_v( std::make_index_sequence<N>{}, i );
}
so if you do get_enum_v<10>(2), it returns an enum_t<...> with 10 alternatives containing the alternative with index 2, which is a constant_v<std::size_t, 2>.
Now we just get a tuple and an index, and we call a function on the tuple element described by the index:
template<class F, class Tuple>
auto apply_to_nth_element( std::size_t i, F f, Tuple tuple ) {
constexpr std::size_t N = std::tuple_size<Tuple>{};
auto Index = get_enum_v<N>( i );
return std::visit( [&](auto I){
return f( std::get<I>(tuple) );
}, Index );
}
you can now do this:
apply_to_nth_element(id, [&](auto& elem) {
s << elem;
}, std::tie(myFloat, myInt));
instead of
DESERIALIZE_MEMBERS(myFloat, myInt)
Live example; Code can be rewritten in versions older than c++17 but gets extremely ugly very fast.
|
71,855,331 | 71,856,031 | How do I make my function return different results depending on type it's been called using templates in C++ | I've been looking for quite a while for an answer to my question, but couldn't find anything that worked.
Basically, I have a Binary Search Tree and a Search function:
T BinarySearchTree::Search(Node *tree, int key) const {
if (tree == nullptr) // if root is null, key is not in tree
return false;
if (key == tree->key) // key is found
return true;
else if (key < tree->key) // recursively look at left subtree if key < tree->key
return Search<T>(tree->left, key);
else // recursively look at right subtree if key > tree->key
return Search<T>(tree->right, key);
}
I want to return different things based on what type it's being called with. E.g. if I call the function as Search<bool>(), I want it to return true or false, but if I call Search<Node*>, I want it to return a pointer. It should kind of look like this:
T BinarySearchTree::Search(Node *tree, int key) const {
if (key == tree->key){ // key is found
if(T = bool)
return true;
else if(T = Node*)
return tree;
else if (T = int)
return tree->key;
}
I'm not even sure if templates are the right way to go here, but any tips for implementation would be appreciated.
| What you are asking for can be done using if constexpr in C++17 and later, eg:
#include <type_traits>
template<typename T>
T BinarySearchTree::Search(Node *tree, int key) const {
static_assert(
std::is_same_v<T, bool> ||
std::is_same_v<T, Node*> ||
std::is_same_v<T, int>,
"Invalid type specified");
if (tree == nullptr) {
if constexpr (std::is_same_v<T, bool>)
return false;
}
else if constexpr (std::is_same_v<T, Node*>) {
return nullptr;
}
else {
return 0; // or throw an exception
}
}
else if (key == tree->key) {
if constexpr (std::is_same_v<T, bool>)
return true;
}
else if constexpr (std::is_same_v<T, Node*>) {
return tree;
}
else {
return tree->key;
}
}
else if (key < tree->key)
return Search<T>(tree->left, key);
else
return Search<T>(tree->right, key);
}
Prior to C++17, a similar result can be accomplished using SFINAE, eg:
#include <type_traits>
Node* BinarySearchTree::InternalSearch(Node *tree, int key) const {
if (tree == nullptr) {
return nullptr;
}
else if (key == tree->key) {
return tree;
}
else if (key < tree->key)
return Search<T>(tree->left, key);
else
return Search<T>(tree->right, key);
}
template<typename T>
typename std::enable_if<std::is_same<T, bool>::value, T>::type
BinarySearchTree::Search(Node *tree, int key) const {
return InternalSearch(tree, key) != nullptr;
}
template<typename T>
typename std::enable_if<std::is_same<T, Node*>::value, T>::type
BinarySearchTree::Search(Node *tree, int key) const {
return InternalSearch(tree, key);
}
template<typename T>
typename std::enable_if<std::is_same<T, int>::value, T>::type
BinarySearchTree::Search(Node *tree, int key) const {
tree = InternalSearch(tree, key);
return tree != nullptr ? tree->key : 0 /* or throw an exception */;
}
Or, using template specialization, eg:
Node* BinarySearchTree::InternalSearch(Node *tree, int key) const {
if (tree == nullptr) {
return nullptr;
}
else if (key == tree->key) {
return tree;
}
else if (key < tree->key)
return Search<T>(tree->left, key);
else
return Search<T>(tree->right, key);
}
template<typename T>
T BinarySearchTree::Search(Node *tree, int key) const {
// throw a suitable exception
}
template<>
bool BinarySearchTree::Search<bool>(Node *tree, int key) const {
return InternalSearch(tree, key) != nullptr;
}
template<>
Node* BinarySearchTree::Search<Node*>(Node *tree, int key) const {
return InternalSearch(tree, key);
}
template<>
int BinarySearchTree::Search<int>(Node *tree, int key) const {
tree = InternalSearch(tree, key);
return tree != nullptr ? tree->key : 0 /* or throw an exception */;
}
|
71,855,546 | 71,857,751 | How to transform a recursive function to an iterative one | I'm trying to convert this recursive function to an iterative one using a stack:
void GetToTownRecursive(int x, Country &country, AList *accessiblesGroup, vector<eTownColor> &cities_colors)
{
cities_colors[x - 1] = eTownColor::BLACK;
accessiblesGroup->Insert(x);
List *connected_cities = country.GetConnectedCities(x);
if (!connected_cities->IsEmpty())
{
ListNode *curr_city = connected_cities->First();
while (curr_city != nullptr)
{
if (cities_colors[curr_city->GetTown() - 1] == eTownColor::WHITE)
{
GetToTownRecursive(curr_city->GetTown(), country, accessiblesGroup, cities_colors);
}
curr_city = curr_city->GetNextNode();
}
}
}
The function takes a town number as an input and returns a list of towns that are connected to that town (directly as well as indirectly).
I'm having difficulty converting it because of the while loop within and because the only action taken after the recursive call is the promotion of the list iterator - curr_city. What should I push into the stack in this case?
Would be glad for your help!
| The action taken after the recursive call is the whole remainder of the while loop (all the remaining iterations). On the stack, you have to save any variables that could change during the recursive call, but will be needed after. In this case, that's just the value of curr_city.
If goto was still a thing, you could then replace the recursive call with:
save curr_city
set x = curr_city->GetTown()
goto start
Then at the end, you have to
check stack
If there's a saved curr_city, restore it and goto just after (3)
Because it's not acceptable to use gotos for this sort of thing (they make your code hard to understand), you have to break up your function into 3 top-level parts:
part 1: all the stuff before the first recursive call, ending with 1-3
part 2: a loop that does all the stuff between recursive calls, ending with 1-3 if it gets to another recursive call, or 4-5 if it doesn't.
part 3: anything that happens after the last recursive call, which is nothing in this case.
Typically there is then a lot of cleanup and simplification you can do after this rearrangement.
|
71,855,689 | 71,855,869 | How delete int* dynamic array? | I get a problem
"free(): invalid pointer
Process finished with exit code 6"
when I am trying to delete dr[1].
Please say why there is the error in current input (str1, str2)?
'''
#include <iostream>
using namespace std;
int64_t myMin(int64_t first, int64_t second) {
return first > second ? first : second;
}
int main() {
string str1, str2;
str1 = "ABRA", str2 = "CADABRA";
int64_t n1 = static_cast<int64_t>(str1.length()), n2 = static_cast<int64_t>(str2.length());
int64_t **dp = new int64_t *[n2 + 1];
for (int i = 0; i <= n2; ++i) {
dp[i] = new int64_t[n1 + 1];
dp[i][0] = 0;
dp[0][i] = 0;
}
for (int64_t i = 1; i <= n2; ++i) {
for (int j = 1; j <= n1; ++j) {
if (str2[i - 1] == str1[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = myMin(dp[i - 1][j], dp[i][j - 1]);
}
}
}
cout << dp[n2][n1];
cout << '\n' << n2 << "\t" << n1 << '\n';
for (int i = n2; i >= 0; --i) {
// There is no problem with uncommented below line. Why?
// if (i != 1)
delete[] dp[i];
}
delete[] dp;
return 0;
}
'''
I use CLion framework.
|
dp[0][i] = 0;
When n2 > n1, this will write over the array dp[0] as i grows.
Adding a bound-check will fix this problem:
if (i <= n1)
dp[0][i] = 0;
In addition, I'd strongly recommend to learn how to debug program.
|
71,856,512 | 71,856,934 | Method of object as method argument of another class in c++ | I have an istance of a class A, that has some methods like:
class A
{
...
public:
bool DoOperation_one(Mytype* pSomeValue);
bool DoOperation_two(Mytype* pSomeValue);
...
bool DoOperation_th(Mytype* pSomeValue);
...
}
Another class, class B, has a pointer to A class and a method BMethod.
Class B
{
...
A* myPtrA;
...
bool BMethod(...); // arguments have to be defined
}
Is it possible to pass to BMethod, methods of A class instance as argument? I will try to be more clear with the follow pseudocode. In same place in class B i call BMethod with myPtrA method as argument (with parameters). I don't want to execute the myPtrA->DoOperation_two(somevalue) at calling time, but only in the BMethod (if statement):
...
bool bVal = BMethod(myPtrA->DoOperation_two(somevalue))
...
bool B::BMethod("valid signature" myFunction)
{
bool bfun=false;
if (myFunction)
{
do_something....
}
return bfun;
}
My goal is to call BMethod argument (DoOperation_one, DoOperation_two or DoOperation_th) in the body of BMethod only. I have been used template, but DoOperation_XXX is executed at calling time.
....
bool bVal = BMethod(myPtrA->DoOperation_two(somevalue));
or
bool bVal = BMethod(myPtrA->DoOperation_one(somevalue));
...
template <typename FunctionT>
bool BMethod(FunctionT myFunc)
{
bool bfun=false;
bool breturn = false;
while (!bfun)
{
if (myFunc)
{
bfun=true;
breturn = some_other_operation();
}
}
return breturn ;
}
Moreover, myFunc contains result of myPtrA->DoOperation_one(somevalue), and doesn't change in the while statement because it has executed at calling time.
Is there any other approach/solution?
| You can pass a member function pointer but then you'll need an A instance to call it and a Mytype* to be passed as parameter:
struct Mytype {};
struct A {
bool DoOperation_one(Mytype* pSomeValue) { return true;}
bool DoOperation_two(Mytype* pSomeValue) { return true;}
bool DoOperation_th(Mytype* pSomeValue) { return true; }
};
struct B {
A a;
template <typename F>
bool BMethod(F f,Mytype* mt) {
bool bfun=false;
bool breturn = false;
while (!bfun) {
if ((a.*f)(mt))
{
bfun=true;
breturn = true;//some_other_operation();
}
}
return breturn ;
}
};
int main() {
Mytype mt;
B b;
b.BMethod(&A::DoOperation_one,&mt);
}
Instead of making BMethod a template, I could have spelled out the type explcitly, it is bool (A::*)(Mytype*). The syntax to call a member function pointer is a little clunky. If a is a pointer to A (like in your code) then it is (a.->f)(mt).
Note that this only makes sense if the value returned from A::DoOperation_xyz changes while B::BMethod is executing. For example when multiple threads are involved. If thats the case you need to be careful with synchronizing access to shared data to avoid data races. If this isnt multi-threaded, I see no reason to make it complicated and BMethod can simply be bool BMethod(bool x).
|
71,856,749 | 71,856,864 | c++ which format is used in this swprintf() | What format does this specify in int swprintf (wchar_t* ws, size_t len, const wchar_t* format, ...); ?
L"x%04.4x "
| A break-down of the parts:
the L prefix specifies a wide format string (wchar_t *, as opposed to char * in [s]printf)
the leading x is not part of the format specifier, same as the trailing space
%x results in a hexadecimal representation of the argument
the 0 specifies the padding - i.e., if the given number is less than the specified number of digits (see next bullet point), it will be padded with 0s
the 4 after that gives the width, i.e. the printed number of digits (but including extra characters such as 0x, in case for example the # prefix would have been given as well)
.4 - 'precision' for floating points, for integers it is the (minimum) number of printed digits
See also for example this answer, and myriads of other format specifier resources, e.g. on cppreference
Note that the combination of a width and a precision can lead to unexpected results; the precision is considered for the number of digits (including the number of 0), and the width is used for the width of the resulting string; examples:
wprintf(L"x%2x\n", 0x618);
wprintf(L"x%.2x\n", 0x618);
wprintf(L"x%0.3x\n", 0x0618);
wprintf(L"x%0.4x\n", 0x0618);
wprintf(L"x%01.4x\n", 0x618);
wprintf(L"x%04.4x\n", 0x618);
wprintf(L"x%010.4x\n", 0x618);
wprintf(L"x%010x\n", 0x618);
Output:
x618
x618
x618
x0618
x0618
x0618
x 0618
x00000618
So as you can see, a "width" less than 4 doesn't change anything about the output, unless the precision also decreases (but a precision less than 3 also does not decrease the number of digits shown, as it wouldn't be possible to represent the number with less digits).
And in the next-to-last line, you see the effect of a large value for width but low precision; the output is right-aligned, but with spaces instead of 0 as prefix.
|
71,856,845 | 71,861,695 | How to detect if function is implemented in installed library? | I have my program for windows, which uses windows system library (let's name it "sysLib"), and it implements function "libFun1". My program can look like this:
#include <sysLib.h>
void myFunction() {
//some magic here
}
int main() {
myFunction();
libFun1();
return 0;
}
later, library gets update, in which new "libFun2" function is added and it perfectly does what my "myFunction" do and even does it better. So I update my program to look like this:
#include <sysLib.h>
int main() {
libFun2();
libFun1();
return 0;
}
I compile it and push update to clients.
But there are some clients, who doesn't have last version of windows and they have the old version of "sysLib" which doesn't implement "libFun2", so program for them doesn't work (doesn't even start).
I figured out, that if i compile my program with "delayimp.lib /DELAYLOAD:sysLib.dll", program is now startable, but falls when "libFun2" is called.
I would like to now update my code to looku something like this:
#include <sysLib.h>
void myFunction() {
//some magic here
}
int main() {
if(/*libFun2 exists*/) {
libFun2();
} else {
myFunction();
}
libFun1();
return 0;
}
How can i detect, if "libFun2" function exists inside library and make logic around it?
I know that in linux is possible to do if(libFun2), but this doesn't work in windows
UPDATE:
I found out, that it can be catched by __try __except combination, but it doesnt work for me...
https://learn.microsoft.com/en-us/cpp/build/reference/error-handling-and-notification?view=msvc-170
| Solution is pretty simple:
#include <sysLib.h>
#include <delayimp.h>
int CheckDelayException(int exception_value)
{
if (exception_value == VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND) ||
exception_value == VcppException(ERROR_SEVERITY_ERROR, ERROR_PROC_NOT_FOUND))
{
// This example just executes the handler.
return EXCEPTION_EXECUTE_HANDLER;
}
// Don't attempt to handle other errors
return EXCEPTION_CONTINUE_SEARCH;
}
void myFunction() {
__try {
libFun2();
return;
} __except (CheckDelayException(GetExceptionCode())) {
myFunction();
}
//some magic here
}
int main() {
myFunction();
libFun1();
return 0;
}
https://learn.microsoft.com/en-us/cpp/build/reference/error-handling-and-notification?view=msvc-170
UPDATE: moved __try into function for better usage in code, if multiple calls are used
|
71,857,372 | 71,857,716 | Why does a method with the same type argument with "const" at the end give an ERROR 0308? | code:
class InArgClass
{
InArgClass(int In) { }
};
class ToolClass
{
public:
void TestFunc(const InArgClass& Name) { }
void TestFunc(int index) const { } // E0308
//void TestFunc(int index) { }; // NO ERROR
};
int main()
{
//std::cout << "Hello World!\n";
ToolClass* m = new ToolClass();
m->TestFunc(100);
}
The class has a method with int argument, so in "const" at end of function int and InArgClass equal?
ERROR 0308: more than one instance of overloaded function
| So, here you are the problem. InArgClass defines a (private) constructor from an int which is not marked explicit.
When you try to call m->TestFunc(100), the compiler has to decide whether:
To promote m (which is non-const) to const and call the int overload (gcc issues a warning but does that);
To try and construct a temporary InArgClass instance from 100 and call the InArgClass const& overload (it will later realize that it cannot as the constructor is private).
There are at least 3 ways to make that call non ambiguous:
Mark the constructor as explicit
class InArgClass
{
explicit InArgClass(int In) { }
};
Mark the first overload as const (if possible)
void TestFunc(const InArgClass& Name) const { }
Make m a ToolClass const*:
ToolClass const* m = new ToolClass();
|
71,858,429 | 71,858,543 | Iterators in C++. How to modify a vector knowing its iterators? | Trying to understand iterators in C++. For example, in the code below we print a vector.
using Iterator = vector<int>::iterator;
void PrintRange(Iterator range_begin, Iterator range_end) {
for (auto it = range_begin; it != range_end; ++it) {
cout << *it << " ";
}
}
int main() {
vector<int> numbers = {5, 3, 2, 1};
PrintRange(begin(numbers), end(numbers));
return 0;
}
// 5 3 2 1
My question is how to properly write a function that takes only two iterators and that modifies the vector. For example, the function my_sort sorts a vector and if we write
my_sort(begin(numbers), end(numbers));
number contains a modified sorted vector.
void my_sort(Iterator range_begin, Iterator range_end) {
// how to modify a vector knowing its iterators ?
}
|
How to modify a vector knowing its iterators?
You can indirect through an input iterator to access the element that it points to. Example:
auto it = std::begin(numbers);
*it = 42;
For example, the function my_sort sorts a vector
A sorting function generally swaps elements around. You can swap to elements pointed by iterators like this:
std::iter_swap(it1, it2);
|
71,858,509 | 71,865,025 | How to deserialize a std::string to a concrete message in Cap'n Proto C++? | I need to decode a message from a std::string object.
I can see how to do this in Java by using a ByteBuffer, but I failed to find a simple C++ equivalent.
More precisely, how to implement this?
const std::string serialized_data = ...; // Source
SomeDataType data = ???; // How to convert from serialized_data to data?
| You can write code like this:
std::string serialized_data = ...;
kj::ArrayPtr<const capnp::word> words(
reinterpret_cast<const capnp::word*>(serialized_data.begin()),
serialized_data.size() / sizeof(capnp::word));
capnp::FlatAraryMessageReader reader(words);
Note that this assumes that the backing buffer of an std::string is always word-aligned. I think this is true, but I am not sure. If it is not aligned, you will get exceptions saying so. In this case it may be necessary to copy the data into an aligned buffer:
auto words = kj::heapArray<capnp::word>(
serialized_data.size() / sizeof(capnp::word));
memcpy(words.begin(), serialized_data.begin(), words.asBytes().size());
capnp::FlatAraryMessageReader reader(words);
Note that while std::string is technically able to store arbitrary bytes, it is not a particularly good data structure for this purpose, since it is optimized for text. For example, it may re-allocate and copy your buffer in order to add a NUL terminator to support .c_str(). I would recommend using a more data-oriented type for byte arrays.
|
71,858,556 | 71,858,709 | How to handle the ownership transfer of a unique pointer's stored raw pointer? | How to handle a scenario where I have a unique pointer with custom deleter, but a 3rd party library's function expects a raw pointer and I pass the stored pointer in the unique_ptr with .get(), but this function takes ownership of the raw pointer.
Example:
Initialize the unique pointers with custom deleter:
std::unique_ptr<BIGNUM, decltype(&BN_free)> r(BN_bin2bn(signature.data(), bnLen, nullptr), &BN_free);
std::unique_ptr<BIGNUM, decltype(&BN_free)> s(BN_bin2bn(signature.data() + bnLen, bnLen, nullptr), &BN_free);
Pass them to the ECDSA_SIG function, which takes the ownership of the r and s unique pointers:
ECDSA_SIG_set0(ecDsaSignature.get(), r.get(), s.get()))
At the end of the scope the custom deleter is called, but it crashes because the r and s were moved. I was thinking about using raw pointers, but what happens if the ECDSA_SIG_set0 function call is unsuccessful, do I have to manually free the r and s variables? Is this the correct way, or is there a more elegant way to handle this scenario?
Thank you in advance.
|
I pass the stored pointer in the unique_ptr with .get(), but this function takes ownership of the raw pointer.
If the function takes ownership, then you should release the ownership from the unique pointer. Otherwise the ownership won't be unique and you will get undefined behaviour due to multiple calls to the deleter. This is what the release member function is for.
but what happens if the ECDSA_SIG_set0 function call is unsuccessful, do I have to manually free the r and s variables?
If the function takes ownership of the pointer, then it is responsible for deleting it (until it transfers the ownership somewhere else). If the function sometimes leaks the pointer, then it is a badly designed API.
What the function does should be specified in its documentation. It would be much better to use std::unique_ptr in the API if it takes ownership.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.