I can pass variables by value to a thread and by reference with std::ref( obj ). But how can I move an object to a thread ?
vendredi 31 décembre 2021
Undefined symbols for architecture x86_64 while make install using Cmake
I'm trying to build a project which contains main.cxx Control.cxx Control.hxx Event.cxx and Event.hxx, but it says:
Undefined Symbols for architecture x86_64
"Control::LoadDataFile()", referenced from:
_main in main.cxx.o
"Control::Control(char const*)", referenced from:
_main in main.cxx.o
"Control::~Control()", referenced from:
_main in main.cxx.o
when I try to make install. Here are my codes: main.cxx inside timeline/app
#include<iostream>
#include"Control.hxx"
#include"Event.hxx"
int main(){
Control usage;
usage.LoadDataFile();
return 0;
}
Control.cxx inside timeline/src
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
#include"Control.hxx"
#include"Event.hxx"
Control::Control(char const* InputDataFile)
:DataFile(InputDataFile)
{
std::cout<<"Welcome to timeline searching system"<<endl;
}
Control::~Control(){
}
void Control::LoadDataFile(){
std::cout<<"Loading data file..."<<endl;
ifstream input_file(DataFile);
while(getline(input_file,line)){
line>>Year>>Month>>Day>>Name>>Content;
Event* event = new Event(Year, Month, Day, Name, Content);
Events.push_back(event);
}
std::cout<<"Loaded all data"<<endl;
}
void Control::CreateEvent(){
}
void Control::DeleteEvent(){
}
void Control::DisplayEvents(){
if(!Events) std::cout<<"Can not find events!"<<endl;
for(std::vector<Evnet*>::iterator ev_iter = Events.begin();
ev_iter != Events.end(); ++ev_iter){
std::cout<<ev_iter->Get("Year")<<"."<<ev_iter->Get("Month")<<"."<<ev_iter->Get("Day")<<": with"<<ev_iter->Get("Name")<<endl;
std::cout<<ev_iter->Get("Content")<<endl;
}
std::cout<<"All events have been displayed."<<endl;
}
void Control::SearchEvent(){
}
Control.hxx inside timeline/src
#include<vector>
#include"Event.hxx"
class Control {
public:
Control(char const* = "../input/timeline.txt");
~Control();
void LoadDataFile();
void CreateEvent();
void DeleteEvent();
void DisplayEvents();
void SearchEvent();
private:
char* DataFile;
std::vector<Event*> Events;
};
Event.cxx inside timeline/src
#include"Event.hxx"
Event::Event(int const InputYear, int const InputMonth, int const InputDay, char const* InputName, char const* InputContent)
:Year(InputYear), Month(InputMonth), Day(InputDay), Content(InputContent), Name(InputName)
{
}
Event::~Event(){
}
Event.hxx inside timeline/src
ifndef Event_hxx_
#define Event_hxx_
template <typename Type>
Type const& Get(Type const& value)
{
return value;
}
class Event {
public:
Event(int const* InputYear, int const* InputMonth, int const* InputDay, char const* InputName, char const* InputContent);
~Event();
private:
int Year;
int Month;
int Day;
std::string Content;
std::string Name;
template <typename Type> friend Type const& Get(Type const& value);
};
#endif
And finally the CMakeLists.txt at source directory
cmake_minimum_required(VERSION 3.3 FATAL_ERROR)
project(TimeLine_Searching_System)
#add source directory
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src)
add_executable(TimeLine_Searching_System app/main.cxx)
#target_link_libraries(TimeLine_Searching_System PUBLIC src)
target_include_directories(TimeLine_Searching_System PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/src"
)
install(TARGETS TimeLine_Searching_System DESTINATION bin)
Could some one tell me what I did wrong? I'm really a noob.
jeudi 30 décembre 2021
Join all files in a folder with specific filename pattern and omitting comments
Disclaimer: I am not expecting someone else to do all this for me (since this deserves a pay). However, any hint will help.
I have the current folder structure:
/components/cht/phrases-*-cht.txt
/components/chs/phrases-*-chs.txt
What I want to do, demonstrated in Makefile-style bash script (for example "cht"):
@> phrases-cht.int && awk 'NR>1 && FNR==1{print ""};1' ./components/cht/phrases-*-cht.txt | sed -e "/^#/d" > ./Build/DerivedData/phrases-cht.int
Which means:
- Concat all files of "phrases-*-cht.txt" from
/components/cht/
into a temporary filephrases-cht.int
(or better somewhere in the RAM if possible). - Remove all lines started with
#
(if possible please also remove inline comments begun with//
).
P.S.: If okay please do not use "boost". Cpp 17 is okay as long as its compiled executables are executable in Windows Vista or Windows 7.
mercredi 29 décembre 2021
unary_function and binary_function are deprecated in C++ 11, and removed in C++ 17. What should we use instead? [duplicate]
I have been reading Effective STL by Meyers.
I came across some sections which mention function adapter objects, such as not1
, bind1st
, bind2nd
. There are apparently a range of such function adapter objects, however I have never encountered these before. Another example is mem_fun
and mem_fun_ref
.
Many of these inherit from unary_function
and binary_function
. Some links are provided below.
https://en.cppreference.com/w/cpp/utility/functional/unary_function
https://en.cppreference.com/w/cpp/utility/functional/binary_function
https://en.cppreference.com/w/cpp/utility/functional/mem_fun
These objects are depreciated in C++ 11, which probably explains why I had not encountered them before.
Why are they deprecated, and what replaces them? My instinct tells me that a lambda can replace such function objects, and while reading the book it did occur to me that some of the sorting operations on STL containers can be described using a lambda instead of a function object.
- Does a lambda completely replace these "adapter functions".
- If so, are function objects still useful post C++ 11? If they have been made obsolete in the STL, does this mean function objects are obsolete everywhere in C++ 11 or do they still have uses?
Global variable and static global variable [duplicate]
Is there any difference in C++ between global variable/const and global static variable/const? Declared in cpp file or a header file.
static const int x1 = someFunction(5);
const int x2 = someFunction(6);
static int x3 = someFunction(5);
int x4 = someFunction(6);
int main()
{
...
Why this is showing error ? even tough it seems all syntax is correct?
Why is *ptr = (*ptr)++ Undefined Behavior
I am trying to learn how to explain the cause of(if any) of undefined behavior in the following cases(given below).
int i = 0, *ptr = &i;
i = ++i; //is this UB? If yes then why according to C++11
*ptr = (*ptr)++; //i think this is UB but i am unable to explain exactly why is this so
*ptr = ++(*ptr); //i think this is not UB but can't explain why
I have looked at many SO posts describing UB for different pointer cases similar to the cases above, but still i am unable to explain why exactly(like using which point(s) from the standard we can prove that they will result in UB) they result in UB.
I am looking for explanations according to C++11(or C++14) but not C++17 and not Pre-C++11.
mardi 28 décembre 2021
Accessing variables of main() function inside signal handler in C++
I want to change the variables declared in the main function using signal handler when an user defined signal is sent to the process. I do not want to use any global variables.
Below is a sample code.
#include <iostream>
#include <csignal>
void signal_handler(int sig) {
// I want to change value of b here
}
int main() {
signal(SIGUSR1, signal_handler);
int a, b = 10;
while(1) {
std::cin >> a;
std::cout << a * b << std::endl;
}
}
In place of 'b', it could be any other type of variable (a socket file descriptor, a mysql connection etc) which the program has to refresh once a signal is sent. Using global variables for all these tasks is not good.
So, please suggest the different methods for achieving it. Thank you.
How is printf() an expression?
I was trying to learn value categories because of an error that I got and stared watching this video by Copper Spice.
They go on to define an expression and as an example provide printf()
at this point in the video (screenshot below).
How is printf()
an expression? I always thought that function calls aren't really an expression when written by themselves. They are more like statements as my beginner mind thinks of it. Moreover, the definition they provide mentions operators and operands but none can be seen with printf
. What am I missing?
The data type that is mentioned is the return value for printf
. What about functions that return void?
Save two strings in one string and reverse in C++ [closed]
How can be possible in C++
merging two fixed length std::string
s (x and y) in one (z) (possibly with the same length) and then recover them from this resulting z std::string
? This would be kind of encoding-decoding procedure.
The following snippet clarifies my question:
std::string x = "Hello World!"; //x.size() = 11
std::string y = "How are you?"; //y.size() = 11
std::string z = merging_function(x, y); //z.size() = 11
...
...other code
...
std::string decoded_x, decoded_y;
decoding_function(z, decoded_x, decoded_y); // From z will be possible recover x and y saving them in decoded_x and decoded_y
std::cout << decoded_x << std::endl; // Hello World!
std::cout << decoded_y << std::endl; // How are you?
Why can't a copy constructor be templated? [duplicate]
I am doing a course C++ Fundamentals for Professionals on educative.io website, it mentioned the above statement added in the question,
I created a small c++ program to experiment the same -
#include<iostream>
using namespace std;
template<typename T1>
class MyTemplateClass
{
public:
T1 data;
MyTemplateClass()
{
cout << "in default const" << endl;
}
MyTemplateClass(const MyTemplateClass& other)
{
cout << "in default copy const - created automatically" << endl;
this->data = other.data;
}
template<typename T>
MyTemplateClass(const MyTemplateClass<T>& other)
{
cout << "in templated copy const" << endl;
this->data = other.data;
}
};
int main()
{
cout << "hello world" << endl;
MyTemplateClass<int> obj;
MyTemplateClass<double> obj2(obj);
MyTemplateClass<int> obj3(obj);
}
For obj3 it calls the default copy constructor which makes sense but for obj2 it calls the templated copy constructor, so I see a use for the constructor that if I have a class that takes T1 = double, we can created an object for it from an object of a class that takes T1 = int.
Does obj2 using template MyTemplateClass(const MyTemplateClass& other) - this function doesn't seem like a valid copy constructor according to the rules of a copy constructor defined in c++ but why is it such a case - since this seems like a valid use case?
lundi 27 décembre 2021
How to make a unique_ptr in a class a friend of another class
class Test;
class Base {
};
class Child : public Base {
friend class Test; // <--- not working?
protected:
Child() {}
};
class Test {
public:
Test() : t{std::make_unique<Child>()} {}
private:
std::unique_ptr<Base> t;
};
There is a base class and a child class as shown, and another class containing a std::unique_ptr<Base> t
, which needs to be initialized with a child object.
However, it's not working, I always get the error: error: ‘Child::Child()’ is protected
.
It doesn't seem that friend class Test
works as expected.
BTW, I'm working with C++14.
In the constructor you get a pointer to a Boolean function,How do I keep the pointer as a field in a class?in. C++
[.h][1] cpp
In the constructor get a pointer to a Boolean function, what is a pointer to a Boolean function in c ++? How do I keep the pointer as a field in a class? [1]: https://i.stack.imgur.com/PV58E.jpg
Parsing stringstream into std::array [duplicate]
I am reading data from a file of the type (0 0 0)
which I would like to put in a std::array
.
When I compile the code I get an error saying that the >>
is not overloaded.
I have:
#include <array>
#include <sstream>
#include <string>
int main(int argCount, char *args[])
{
std::string tst ("(0 0 0)");
std::istringstream is (tst);
std::array<double, 3> myVec;
is >> myVec;
return 0;
}
How can I overload the >>
operator to collect the data?
Would really appreciate the help.
Vector push_back returns invalid conversion [closed]
Im new to cpp vectors and i keep encountering this issue
error: no matching function for call to ‘push_back(const char [6])’
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> names;
names.push_back("Lewis");
names.push_back("Mark");
names.push_back("Reece");
names.push_back("Max");
for(int i = 0; i < names.size(); i++)
cout << names[i] << '\n';
return 0;
}
This is the error
test.cpp: In function ‘int main()’:
test.cpp:6:26: error: no matching function for call to ‘push_back(const char [6])’
6 | names.push_back("Lewis");
| ^
In file included from /usr/include/c++/9/vector:67,
from test.cpp:1:
/usr/include/c++/9/bits/stl_vector.h:1184:7: note: candidate: ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]’ <near match>
1184 | push_back(const value_type& __x)
| ^~~~~~~~~
/usr/include/c++/9/bits/stl_vector.h:1184:7: note: conversion of argument 1 would be ill-formed:
test.cpp:6:19: error: invalid conversion from ‘const char*’ to ‘std::vector<int>::value_type’ {aka ‘int’} [-fpermissive]
6 | names.push_back("Lewis");
| ^~~~~~~
| |
| const char*
In file included from /usr/include/c++/9/vector:67,
from test.cpp:1:
/usr/include/c++/9/bits/stl_vector.h:1200:7: note: candidate: ‘void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]’ <near match>
1200 | push_back(value_type&& __x)
| ^~~~~~~~~
/usr/include/c++/9/bits/stl_vector.h:1200:7: note: conversion of argument 1 would be ill-formed:
test.cpp:6:19: error: invalid conversion from ‘const char*’ to ‘std::vector<int>::value_type’ {aka ‘int’} [-fpermissive]
6 | names.push_back("Lewis");
| ^~~~~~~
| |
| const char*
test.cpp:7:25: error: no matching function for call to ‘push_back(const char [5])’
parameters r=0 , i=0 in a constructor
so I was just learning about polymorphism in oops , I was being taught operator overloading in a program that adds complex numbers; so there is this class and it's constructor but the constructor is like
complex(int r=0 , i=0){...}
my question is what does r=0 mean as a parameter ? what I am guessing is when I don't pass the values in the constructor when creating an object then the program takes 0 as default value;
if so then can I do the same with normal functions ?
what is this + before u8 string literal prefix for?
when I was reading codecvt
example in cppref, I noticed this line:
std::string data = reinterpret_cast<const char*>(+u8"z\u00df\u6c34\U0001f34c");
Any idea what is that +
before u8
for? Because I removed it and nothing changed in result.
dimanche 26 décembre 2021
Is it "correct" to specify class-member mutex 'mutable' for the purpose of much-more 'const' member functions?
In many cases, many member-functions could be specified 'const' - they don't modify any data-members of the class ...almost: they do lock/unlock the class mutex. Is it a good practice to specify, in that case, the mutex 'mutable'? ...otherwise, it will impossible to specify get_a(), get_b(), get_c(), get_d() 'const'.
--
A mere example. Lets say that 'example' is a thread-safe class and that m_mutex protects its shared resources that get_a(), get_b(), get_c(), get_d() do not modify:
#include <mutex>
class example
{
public:
size_t get_a(void) const {
std::lock_guard lck(m_mutex);
return m_str.length() + a;
};
size_t get_b(void) const {
std::lock_guard lck(m_mutex);
return m_str.length() * 2 + a + b;
};
size_t get_c(void) const {
std::lock_guard lck(m_mutex);
return m_str.length() * 4 + a + b;
};
size_t get_d(void) const {
std::lock_guard lck(m_mutex);
return m_str.length() * 8 + a;
};
size_t modify_something() {
std::lock_guard lck(m_mutex);
if (m_str.length() < 1000) {
m_str.append(".");
a++;
b++;
}
};
protected:
mutable std::mutex m_mutex;
std::string m_str;
int a = 0, b = 0;
};
samedi 25 décembre 2021
sudoku solver repeting number 1 in invalid places
Hi I'm doing a project in college and it consist in solving a sudoku in a certain way. First we look for the possible numbers in one position and then we compare with the possible numbers in the positions in the same ror, colum and 3x3. If there is one compulsory value we put it in the sudoku, if not we jump to the next position. My code works mainly well, but sometimes I don't know why it assigns the number 1 in a position where it's invalid because number 1 it's already in the row/column/3x3.
#include <iostream>
#include <vector>
using namespace std;
typedef vector<vector<int>> Matrix;
int charaint(char colum){
return colum-'A'+1;
}
char intachar(int colum){
return char(colum-1+'A');
}
//looking in the row for possible values in a position.
bool en_fila(const Matrix sudoku, int fil, int i){
bool trobat = false;
for (int col = 0; col < 9 and not trobat; col++){
if ((int)sudoku[fil][col] == i)
trobat = true;
}
return trobat;
}
//looking in the column for possible values in a position.
bool en_columna(const Matrix sudoku, int col, int i){
bool trobat = false;
for (int fil = 0; fil < 9 and not trobat; fil++){
if ((int)sudoku[fil][col] == i)
trobat = true;
}
return trobat;
}
//looking in the 3x3 for possible values in a position.
bool en_quadrat(const Matrix sudoku, int inifil, int inicol, int i){
bool trobat = false;
for (int fil = 0; fil < 3 and not trobat; fil++){
for (int col = 0; col < 3 and not trobat; col++){
if (sudoku[fil+inifil][col+inicol] == i)
trobat = true;
}
}
return trobat;
}
//looking if a value is possible in a position
bool es_possible(const Matrix sudoku, int fil, int col, int i)
{
return !en_fila(sudoku, fil, i) and !en_columna(sudoku, col, i) and !en_quadrat(sudoku, fil-fil%3, col-col%3, i);
}
//creating a vector with the possible values in a position
vector<int> possibles_en_casella(const Matrix sudoku, int fil, int col){
vector<int> p;
for (int i = 1; i <= 9; i++){
if (es_possible(sudoku, fil, col, i))
p.push_back(i);
}
return p;
}
//comparing vectors of the diferent positions of a row with a the vector of possibilities in a single position
bool possible_en_fila(const Matrix sudoku, int fil, int col, vector<int> p, int i){
bool trobat = false;
vector<int> paux;
for (int c = 0; c < 9 and not trobat; c++){
if ((col != c) and (sudoku[fil][c] == 0)){
paux = possibles_en_casella(sudoku, fil, c);
for (int j = 0; j < int(paux.size()); j++){
if (paux[j] == p[i]){
trobat = true;
}
}
}
}
return trobat;
}
//comparing vectors of the diferent positions of a column with a the vector of possibilities in a single position
bool possible_en_columna(const Matrix sudoku, int fil, int col, vector<int> p, int i){
bool trobat = false;
vector<int> paux;
for (int f = 0; f < 9 and not trobat; f++){
if ((fil != f) and (sudoku[f][col] == 0)){
paux = possibles_en_casella(sudoku, f, col);
for (int j = 0; j < int(paux.size()); j++){
if (paux[j] == p[i]){
trobat = true;
}
}
}
}
return trobat;
}
//comparing vectors of the diferent positions of a 3x3 with a the vector of possibilities in a single position
bool possible_en_quadrat(const Matrix sudoku, int fil, int col, vector<int> p, int i){
bool trobat = false;
int inicol = (col-col%3);
int inifil = (fil-fil%3);
vector<int> paux;
for (int f = 0; f < 3 and not trobat; f++){
for (int c = 0; c < 3 and not trobat; c++){
if ((f+inifil != fil) and (c+inicol != col) and (sudoku[f+inifil][c+inicol] == 0)){
paux = possibles_en_casella(sudoku, f+inifil, col+inicol);
for (int j = 0; j < int(paux.size()); j++){
if (paux[j] == p[i]){
trobat = true;
}
}
}
}
}
return trobat;
}
//comparing vectors of the diferent positions with a the vector of possibilities in a single position
vector<int> vector_possibles_en_casella(const Matrix sudoku, int fil, int col){
vector<int> p = possibles_en_casella(sudoku, fil, col);
vector<int> paux;
if ((int(p.size())) == 1 and (p[0] != 0)) return p;
else{
for (int i = 0; i < int(p.size()); i++){
if (!possible_en_fila(sudoku, fil, col, p, i) and !possible_en_columna(sudoku, fil, col, p, i) and !possible_en_quadrat(sudoku, fil, col, p, i)){
paux.push_back(i);
}
}
return paux;
}
}
//print the sudoku
void imprimir_sudoku(Matrix sudoku){
cout << " A B C D E F G H I" << endl;
for (int fil = 0; fil < 9; fil++){
if (fil == 3 or fil == 6){
cout << " -------+-------+-------" << endl;
}
cout << fil+1 << " ";
for (int col = 0; col < 9; col++){
if (col == 2 or col == 5){
if (sudoku[fil][col] == 0) cout << " . |";
else cout << " " << sudoku[fil][col] << " |";
}
else{
if (sudoku[fil][col] == 0) cout << " .";
else cout << " " << sudoku[fil][col];
}
}
cout << endl;
}
cout << endl;
}
int main(){
int fil, val;
char op, columna;
Matrix sudoku(9, vector<int> (9));
for (int f = 0; f < 9; f++){
for (int c = 0; c < 9; c++){
cin >> sudoku[f][c];
}
}
Matrix sudokuinicial = sudoku;
while (cin >> op and op != 'Z'){
//prints the vector of possible values in a given position
if (op == 'A'){
cin >> fil >> columna;
int col = charaint(columna);
if (sudoku[fil-1][col-1] != 0) cout << fil << columna << ": []";
else{
vector<int> p = possibles_en_casella(sudoku, fil-1, col-1);
cout << fil << columna << ": [" << p[0];
if (p.size() > 1){
for (unsigned int j = 1; j < p.size(); j++){
cout << ", " << p[j];
}
}
cout << "]";
}
cout << endl;
}
//looks if the given number is vaild in the given position
if (op == 'B'){
cin >> fil >> columna >> val;
int col = charaint(columna);
if (sudokuinicial[fil-1][col-1] != 0) cout << fil << columna << ": Casella no modificable" << endl;
else {
Matrix sudokuaux = sudoku;
sudokuaux[fil-1][col-1] = 0;
if (not hi_es(val,possibles_en_casella(sudokuaux, fil-1, col-1))){
cout << fil << columna << ": " << val << " es un valor no possible" << endl;
}
else{
sudoku[fil-1][col-1]=val;
}
}
}
//prints actual sudoku
if (op == 'C'){
imprimir_sudoku(sudoku);
}
if (op == 'R'){
Matrix sudokurini;
while (sudokurini != sudoku){
sudokurini = sudoku;
for (int i = 0; i < 9; i++){
for (int j = 0; j < 9; j++){
if (sudoku[i][j] == 0){
vector<int> paux = vector_possibles_en_casella(sudoku, i, j);
if ((int(paux.size()) == 1) /*and (paux[0] != 0)*/){
sudoku[i][j] = paux[0];
char columna = intachar(j+1);
cout << "A la casella (" << i+1 << "," << columna << ") hi ha d'anar un " << paux[0] << endl;
}
}
}
}
imprimir_sudoku(sudoku);
}
}
}
}
I just copied the full code but my problem is when 'R' is the input(instruction to solve the sudoku), options A, B, and C are ok. I think the problem is in this function:
//comparing vectors of the diferent positions with a the vector of possibilities in a single position
vector<int> vector_possibles_en_casella(const Matrix sudoku, int fil, int col){
vector<int> p = possibles_en_casella(sudoku, fil, col);
vector<int> paux;
if ((int(p.size())) == 1 and (p[0] != 0)) return p;
else{
for (int i = 0; i < int(p.size()); i++){
if (!possible_en_fila(sudoku, fil, col, p, i) and !possible_en_columna(sudoku, fil, col, p, i) and !possible_en_quadrat(sudoku, fil, col, p, i)){
paux.push_back(i);
}
}
return paux;
}
}```
Sorry the functions are in my language(catalan).
std::move Bug Spotted in C++ Primer 5th Edition
I looked at an example in C++ Primer explaining std::move
. The example is as follows:
int &&rr1 = 42;
int &&rr3 = std::move(rr1);
In the explanation of the above code snippet, it is written that:
Calling move tells the compiler that we have an lvalue that we want to treat as if it were an rvalue. It is essential to realize that the call to move promises that we do not intend to use
rr1
again except to assign to it or to destroy it. After a call to move, we cannot make any assumptions about the value of the moved-from object.
My first question is that: Can i now safely write std:: cout << rr1;
? Since in the above quote paragraph, it is written that we cannot make any assumptions about the value of the moved-from object so is it guaranteed by the standard that std::cout << rr1;
is safe(not UB or depends on implementation etc)?
Here is another example,
std::string str = "abc";
auto&& str2 = std::move(str);
cout << str; // is this safe(not UB or depends on implementation)
Similarly, in the above snippet, is it safe to use the value of str
like cout << str;
?
If yes, then is this a mistake/bug in the book C++ Primer by Stanley.
Why Sutter suggests store only values and smart pointers in containers?
I'm reading Herb Sutter's C++ Coding Standards
item 79:
Store objects of value in containers: Containers assume they contain value-like types, including value types (held directly), smart pointers, and iterators.
I'm afraid that I didn't get the idea of why.
Question 1: when Sutter says contain
, does he mean own
? like "Containers assume they own value-like types"?
Question 2: besides value types, smart pointers, and iterators, what else types can be stored? for example, reference? Why reference is not recommended to be stored in containers?
Thanks
How to properly read and parse piped stream on thread
I am writing a program that uses 2 threads in C++, the first one that waits for commands and prints the outputs on std::cout
asynchronously and the second one that gathers this output and parses it via a pipe.
firstThread = std::thread([] () {
Lib::loop(); // waits for commands from cin `(getline(cin, ...))`, does its magic and prints the output
});
CONSOLE OUTPUT:
> first result
> second result
> third result
...
To pass those informations to a second thread I close std::cout
, open a pipe, and redirect it to the second one via a file descriptor
int read_out_fd;
int write_out_fd;
int vals[2];
pipe(vals);
read_out_fd = vals[0];
write_out_fd = vals[1];
close(STDOUT_FILENO);
dup(write_out_fd)
using the read()
method in the second thread I wait for those outputs to be written by firstThread
, gather them as they come, and parse them to build an array of string.
readThread = std::thread([] () {
#define MAX_LEN 10
char buffer[MAX_LEN+1] = {0};
string output;
vector<string> messages;
while(read(read_out_fd, buffer, MAX_LEN)) {
output += buffer;
if(strlen(buffer) < MAX_LEN)
output += '\n';
memset(buffer, 0, sizeof buffer);
if (output.find('\n')) {
stringstream stream(output);
string message;
vector<string> messages_buffer;
while(getline(stream, message)){
messages_buffer.push_back(message);
}
output = messages_buffer.back();
messages_buffer.pop_back();
messages.insert( messages.end(), messages_buffer.begin(), messages_buffer.end());
}
}
});
This actually works, it transforms the stream of outputs from the first thread into an array (vector) of strings as they come:
messages : { "first result", "second result", "third result" }
However, I can feel that this method is convoluted. I am new to c++ and I don't know if this is the proper way to tackle this problem. Is there a better/easier way to gather and parse this output?
Notes:
- I cannot modify anything inside
Lib::loop
, this is a third part library. - I cannot
fork()
either since this c++ code is embedded in an iOS project (or I didn't find how) - I tried all the methods on this post but none of them worked for me for various reasons (missing libraries such as boost which I don't want to use, c++11 requirements etc...)
vendredi 24 décembre 2021
C++ input validation and the input is skipped
void grade::getName(){
std::cout << "Enter your name: >> ";
getline(std::cin, name);
extractLastName();
}
void grade::getInput(){
std::cout << "\nProfessor " << name << " please enter the grade >> ";
std::cin >> grade;
grades.push_back(grade);
std::cout << "\nAnymore grade? Yes = 1, No = 0 >> ";
std::cin >> option;
validation();
}
void grade::medianFun(){
std::sort(grades.begin(), grades.end());
unsigned short med = grades.size() / 2;
if((grades.size() % 2) == 0)
median = ((double)grades.at(med) + (double)grades.at(med-1)) / 2;
else
median = grades.at(med);
}
void grade::mean(){
for(auto i : grades)
totalGrade += i;
average = ((double)totalGrade / (double)grades.size());
}
void grade::validation(){
std::cin.sync();
while(option != 1 or option != 0){
std::cout << "Please enter 1 to add more grade, 0 to exit and view the stat " << std::endl;
std::cin >> option;
if(option == 1 or option == 0)
break;
}
}
void grade::menu(){
getName();
do{
getInput();
}while(option);
print();
std::cout << "\n";
}
int main(){
grade gradeObj;
gradeObj.menu();
return 0;
}
So basically the function validation is causing the problem. Input is skipped, and it will become an infinity loop. I have seen most of the posts are talking about having cin first and get line after, and they use cin.ignore()
or cin.sync()
to solve the problem. However; those do not work for my situation.
Sample in output
jcmbp:do grading jeffreychan$ g++ -g -Wall -O3 -std=c++11 grading.cpp -o grade && time ./grade
Enter your name: >> J C
Professor C please enter the grade >> 90
Anymore grade? Yes = 1, No = 0 >> 9
Please enter 1 to add more grade, 0 to exit and view the stat
Professor C please enter the grade >>
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat
Professor C please enter the grade >>
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat
Professor C please enter the grade >>
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat
Professor C please enter the grade >>
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat
Professor C please enter the grade >>
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat
Displaying part of number with brackets
So I'm writing code for math assignment i have to represent number from variable the following way: Let's say that's the number from variable A : 18,223443934844. And that how it should print like : 18,223(443934844). Numbers in the brackets are supposed to be the repeating part of the numbers after the decimal comma.
Had the idea to put every element of the number in array and then put the brackets whenever necessary but don't really know how to do it.
I'd appreciate every advice.
Why primitive to class type conversion destroys object values?
Why in the below code when I set c1 = 10
destroys all other values of variables (a
, b
, c
) of the object. The statement should call the constructor and as the constructor is defined it sets the values of a
to 10
, but when I try to access values of b
and c
; it is giving me garbage values.
#include<iostream>
using namespace std;
class abc{
private:
// properties
int a,b, c;
public:
void setdata(int x,int y)
{
a = x;
b = y;
}
void showdata(){
cout << "a = " << a << " b = " << b << "\n";
}
// constructors
abc(){}
abc(int k)
{
a=k;
}
};
int main()
{
abc c1; // object intialization
c1.setdata(6,7); // setting values of properties
c1.showdata(); // printing values
c1 = 10; // primitive to class type conversion, constructor is being called
c1.showdata(); // why value of b and other variables is getting changed ?
return 0;
}
Should I move on return when variables are not local
A have a few questions regarding copy elision and move. Let's assume I have the following code:
class A {};
class B {
public:
A get1() const {
A local_var;
return local_var;
}
A get1bad() const {
A local_var;
return std::move(local_var);
}
A get2() const {
return member_var;
}
A get3() const {
return std::move(member_var);
}
private:
A member_var;
};
I read a lot of people saying to not do move on return. From what I gather it's because with copy elision, on case get1, the compiler will not call constructor + move constructor but rather just one call to the default constructor, while case get1bad forces the compiler to call constructor + move.
My question is regarding cases where the variable is not local (get2 vs get3). In that case, the variable is constructed anyway in the class. In get2 there's not really any optimization that I can see being possible. In this case, if I don't really care about ensuring class B has a valid A object, wouldn't it be better to actually move? Wouldn't it just call the move constructor which is generally cheaper than the copy constructor?
jeudi 23 décembre 2021
how to sort letters followed by its position to create a word using linked list in c++
my program is for sorting a letters entered by the user and each letter is followed by its position to create a word using linked list " the word should be ended by -1 to stop insertion". my problem is when I enter the input nothing happen after that I think the problem is at the function printList(Node* head) put I cant get it .
include <iostream>
using namespace std;
/* Link list node */
class Node
{
public:
int data;
char x;
Node* next;
void sortedInsert(Node** head_ref, Node* new_node);
Node* newNode(int new_data);
void printList(Node* head);
~Node() {};
};
/* function to insert a new_node
in a list. Note that this
function expects a pointer to
head_ref as this can modify the
head of the input linked list
(similar to push())*/
void Node::sortedInsert(Node** head_ref, Node* new_node)
{
Node* a = new Node();
// Advance s to index p.
Node* current;
// Special case for the head end
if (*head_ref == NULL || (*head_ref)->data >= new_node->data)
{
new_node->next = *head_ref;
*head_ref = new_node;
}
else
{
// Locate the node before the point of insertion
current = *head_ref;
while (current->next != NULL && current->next->data < new_node->data)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
/* BELOW FUNCTIONS ARE JUST
UTILITY TO TEST sortedInsert */
/* A utility function to
create a new node */
Node* newNode(char x, int new_data)
{
/* allocate node */
Node* new_node = new Node();
/* put in the data */
new_node->data = x;
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
/* Function to print linked list */
void Node::printList(Node* head)
{
Node* temp = head;
Node* temp2 = head;
while (temp != NULL) {
cout << temp->data << temp2->data << " ";
temp = temp->next;
temp2 = temp2->next;
}
}
int main()
{
/* string s;
cout << " enter the letters to sort it : " << endl;
cin >> s;
sortString(s);
cout << endl;*/
long nums[1000];
char x[1000];
cout << " enter exprission followed by its positin to sort it 'enter -1 to end it' : ";
for (int i = 0; i < 1000; i++)
{
for (int j = 0; j < 1000; j++)
{
cin >> x[i] >> nums[j];
if (nums[j] == -1)
break;
Node* head = NULL;
Node* new_node = newNode(x[i], nums[j]);
sortedInsert(&head, new_node);
}
Node* head = NULL;
cout << "Created Linked List\n";
printList(head);
}
return 0;
}
Is there a performance benefit in using a pool of threads over simply creating threads?
I was wondering is there are performance benefits to using a pool of threads over simply creating threads and allowing the OS to queue and schedule them.
Say I have 20 available threads and I have 60 tasks I want to run on these threads, say I have something like;
void someTask() {
//...performs some task
}
// say std::thread::hardware_concurrency() = 20
std::vector<std::thread> threads;
for (int i = 0; i < 60; i++) {
threads.push_back(std::thread(someFunc);
}
std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});
Is there a benefit to instead creating a pool with 20 threads and giving each of these another 'task' when a thread becomes free? I assume that there is some overhead in spawning a thread, but are there other benefits to creating a pool for such a problem?
mercredi 22 décembre 2021
understanding move semantic for a shared_ptr with an rvalue function call
In the following small program I have two examples of using move
with shared_ptr
.
The first example behaves as I expected and the ownership of the shared_ptr
p
is assigned to the new pointer p2
. After the assignment p
is an invalid pointer.
I would expect the same to happen also in the second example, but it does not. The precise questions are embedded as comments in the source code. What is wrong in my reasoning?
#include <memory>
#include <iostream>
using namespace std;
void foo(shared_ptr<int>&& p)
{
std::cout << "zoo: " << p.use_count() << "\n";
// when this function terminates, should the destructor of p
// decrement the ref counter and destroy the pointed object?
}
void example1()
{
auto p = make_shared<int>(0);
std::cout << "count before move: " << p.use_count() << "\n";
shared_ptr<int> p2(move(p));
std::cout << "count after move: " << p.use_count() << "\n"; // output 0: ownership transferred to p2
}
void example2()
{
auto p = make_shared<int>(0);
std::cout << "count before move: " << p.use_count() << "\n";
foo(move(p));
std::cout << "count after move: " << p.use_count() << "\n";
// output 1: Why is this not zero?
//Why has ownership not transferred to the argument of the function foo?
}
int main()
{
example1();
example2();
return 0;
}
"expected primary-expression before ‘{’ token" when calling overloaded "<<" with customized data type
I have a simple class 'A' with the following contents:
class A {
public:
struct data_t {
int32_t val;
data_t(int32_t _val) :
val(_val) {
;
};
};
A& operator << (const data_t &data) {
printf("[%s] %d\n", __func__, data.val);
return *this;
};
void func(const data_t &data) {
printf("[%s] %d\n", __func__, data.val);
}
};
I tried the following codes and got:
A a;
a<<{100}; //"expected primary-expression before ‘{’ token"
a<<A::data_t{100}; //OK.
a.func({100}); //OK.
Why a<<{100}; is NG and a.func({100}); is OK?
I don't want to use the second sentence because it is too long and complicated to read.
About func(const int&) and func(const int)
#include <iostream>
class Account {
public:
static double GetCircumference(const double &dR) { return 2 * dR * 3.1415926; }
static constexpr double cd = 3.0;
};
// constexpr double Account::cd;
int main()
{
std::cout << Account::GetCircumference(Account::cd) << std::endl;
}
The code is wrong unless I remove the "//". But if I only change (const double &dR) to (const double dR), it becomes ok too. Why?
the best design for mapping enums to const classes
I have this example that works : I create an object that implements "PartInterface" for each value of the enum and add them in a map. But I don't find this satisfactory, because everything could be inferred at compile time rather than at runtime. Is there a more elegant way to do this in c++ 11? Another solution would be to build the "YearPart", "MonthPart" and "DayPart" objects at each call of the "get" function, but it seems to me less efficient...
#include <iostream>
#include <map>
#include <memory>
struct Date{
int year;
int month;
int day;
};
class PartInterface{
public:
virtual const std::string & getName()const=0;
virtual int getValue(const Date& d)const=0;
virtual ~PartInterface(){}
};
class Part : public PartInterface{
public:
Part(const std::string& name):_name(name){}
const std::string & getName()const{
return _name;
}
virtual int getValue(const Date& d)const=0;
private:
std::string _name;
};
class YearPart : public Part{
public:
YearPart():Part("year"){}
int getValue(const Date& d)const{
return d.year;
}
};
class MonthPart : public Part{
public:
MonthPart():Part("month"){}
int getValue(const Date& d)const{
return d.month;
}
};
class DayPart : public Part{
public:
DayPart():Part("day"){}
int getValue(const Date& d)const{
return d.day;
}
};
enum DatePart{
Year,
Month,
Day
};
class Parts{
public:
Parts(){
_map[Year].reset(new YearPart());
_map[Month].reset(new MonthPart());
_map[Day].reset(new DayPart());
};
const PartInterface& get(const DatePart& date_part)const{
return * (_map.find(date_part)->second);
}
private:
std::map<DatePart, std::unique_ptr<PartInterface> > _map;
};
int main() {
Date d({2016, 7, 23});
const Parts parts;
std::cout << "Date "
<< parts.get(Year).getValue(d) << " "
<< parts.get(Month).getValue(d) << " "
<< parts.get(Day).getValue(d) << std::endl;
return 0;
}
mardi 21 décembre 2021
Syntax error; string is not being accepted in if statement. ( C++ ) [duplicate]
In this code I tried to use getline() for getting full sentence as input from user and show results. It's a very basic program. I was trying to make small interactive platform.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a;
string b;
string b1 = "I am fine";
std::cout << "Hello, Enter 1 to continue...." << std::endl;
std::cin >> a;
if(a==1){
std::cout << "How are you?" << std::endl;
getline(std:: cin, b);
}else{
cout<<endl;
}
int c;
if(b == b1){
std::cout << "Gald to know that, press 2 to continue..." << std::endl;
cin>>c;
}else{
std::cout<< "Bye" <<endl;
}
return 0;
}
How do you write a simple stream in cpp?
I'm a 13 year old who just started learning about using istream
& ostream
so you can create your own IO stream? If this is incorrect please let me know... I'm still very confused on how this actually works.
creating a class vector that does not delete it's content
I am a beginner , so i wanted to ask , can we create a class object vector/array , that does not delete it's content when i close the program like , so like I want a customer record , but whenever if we try to restart the program we need to enter the customer details again and again ... how to prevent that from happening
#include <iostream>
#include <vector>
using namespace std;
class customer{
public:
int balance;
string name;
int password;
};
int main(){
vector <customer> cus;
...
if(choice == 1){
cout << cus[i].balance
}
return 0;
}
lundi 20 décembre 2021
How can I do to keep the value of a variable after a do while loop?
I have been coding a program to simulate a roulette of a casino, thing is that every time I try to repeat the game after is finished I want the game to keep going and the money to be the same, so if you have lost money you start with that certain money, here is the code (It's in Spanish but I think it's pretty clear):
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int num, pri, randum, num2, op, num3 = 10000, col = randum, rep, clear;
int main() {
do {
int num4 = op;
cout << "Escoja la opción de la que apostar.\n";
cout << "1 - Apostar a un número. \n2 - Apostar a un color \n";
cout << "Elija opción: ";
cin >> pri;
cout << " \n";
cout << " \n";
switch (pri) {
case 1: {
srand(time(0));
randum = rand() % 37 + 1; //si poner 37 + 1 te va cojer números hasta el 37 no?
if (num4 != 10000) {
cout << "Su saldo actual es " << num3 << " €\n";
} else {
cout << "Su saldo actual es 10000 €\n";
}
cout << "Ha elegido apostar a un número\n";
cout << "Introduzca el dinero que quiere apostar -->\n";
cin >> num;
cout << "Ahora introduzca el número que desee entre el 0 y 36 -->\n";
cin >> num2;
if (num2 == randum) {
op = num3 + num;
cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << op << " €\n";
} else {
op = num3 - num;
cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << op << " €\n";
cout << "¿Quieres volver a jugar?\n- Sí -> 1\n- No -> 2\n";
cin >> clear;
if (clear == 1) {} else if (clear == 2) {
cout << "Bien, suerte en la próxima tirada.\n\n";
}
}
break;
}
case 2: {
if (num3 == 10000) {
cout << "Su saldo actual es 10000 €\n";
} else {
cout << "Su saldo actual es " << num3 << " €\n";
}
cout << "Ha elegido apostar a un color\n";
cout << "Introduzca el dinero que quiere apostar -->\n";
cin >> num;
srand(time(0));
randum = rand() % 2 + 1;
cout << "Ahora escoja rojo (1) o negro (2) -->\n";
cin >> col;
if (col == randum) {
op = num3 + num;
cout << "\n¡Enhorabuena! Has ganado! Ahora tienes " << op << " €";
} else {
op = num3 - num;
cout << "\nLo sentimos... Has perdido la apuesta, ahora tienes " << op << " €";
}
cout << "¿Quieres volver a jugar?\n- Sí -> 1\n- No -> 2\n";
cin >> clear;
if (clear == 1) {} else if (clear == 2) {
cout << "Bien, suerte en la próxima tirada.\n\n";
}
}
}
} while (clear == 1);
return 0;
}
Simple program to efficiently remove the elements from vector in C++, Is there any better solution than this?
Is there any more efficient solution than this to remove some elements of the vector?
{
vector<int> v{1,2,3,4,5,6,7,8,9,10};
for (int i = 0; i < v.size(); i++)
{
if(v[i] % 2 == 0)
{
auto it2 = std::remove(v.begin(), v.end(), v[i]);
v.erase(it2);
}
}
for (auto it = v.begin(); it != v.end(); it++)
{
cout << *it;
}
return 0;
}
dimanche 19 décembre 2021
Get std::set comparison as function parameter / complemet of a set without universal set
I have this .cpp file and I have to write the methods set_union, subset, complement, and contains. My two problem is first: How can I have a complement without a universal set and how will ("Hi","Hello","Aloha","Ciao")
sets complement give "C++"
as a member.
Second with the set a and x it gives me an error :
no instance of constructor "set_operations<T>::set_operations [with T=std::string]" matches the argument list -- argument types are: (std::set<std::string, string_size_less, std::allocator<std::string>>)
and
no suitable user-defined conversion from "std::set<std::string, std::greater< std::string>, std::allocator< std::string>>" to "std::set<std::string, std::less< std::string>, std::allocator< std::string>>" exists
How can I get the sets comparison as function parameter?
main.cpp:
#include <iostream>
#include "setops.h"
#include <set>
#include "setops.h"
#include <algorithm>
#include <iterator>
#include <string>
#include <numeric>
struct string_size_less
{
bool operator()(const std::string &a,
const std::string &b)
{
return a.size() < b.size();
}
};
const int max = 1000;
bool check()
{
std::set<int> si;
for (int i = 0; i < max; ++i)
{
si.insert(i);
}
std::set<std::string> msgs;
msgs.insert("Hi");
msgs.insert("Hello");
msgs.insert("Ciao");
msgs.insert("Aloha");
set_operations<std::string> ops(msgs);
const set_operations<std::string> cops(msgs);
set_operations<int> opi(si);
for (int i = 0; i < max; ++i)
{
opi.complement();
}
ops.complement();
if (!cops.contains("Hi") || !opi.contains(max / 2) ||
ops.contains("Ciao") || ops.contains("Aloha") ||
opi.contains(2 * max) || cops.contains("?") ||
cops.contains("NullPointerException") || !ops.contains("C++"))
{
return false;
}
std::set<std::string> w;
w.insert(":-)");
w.insert(":-P");
w.insert("Ciao");
ops.set_union(w);
std::set<int> nums;
nums.insert(max / 2);
nums.insert(max / 3);
nums.insert(max);
opi.complement();
opi.set_union(nums);
opi.complement();
if (opi.contains(max / 2) || !opi.contains(max / 4) ||
!ops.subset(w) || cops.subset(w) ||
ops.contains("Hi") || !ops.contains("Ciao") ||
!ops.contains(":-P") || cops.contains(":-P"))
{
ops.complement();
return false;
}
std::set<std::string, string_size_less> x;
x.insert("Hello");
x.insert("Ciao");
std::set<std::string, std::greater<std::string>> a;
a.insert(":-o");
set_operations<std::string> m(x);
m.set_union(a);
return (!m.contains(":-/") && !m.subset(msgs));
}
int main()
{
std::cout
<< "Your solution is "
<< (check() ? "" : "not ")
<< "ready for submission."
<< std::endl;
}
setops.h:
#ifndef SET
#define SET
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <set>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <string>
#include <numeric>
class Comp
{
bool comp;
};
template <typename T>
class set_operations
{
private:
std::set<T> data; // data
public:
set_operations::set_operations(const std::set<T> &s) : data(s.begin(), s.end()) {}
void complement();
bool contains(T search) const;
void set_union(std::set<T> set2);
bool subset(std::set<T> set2) const;
void write();
set_operations &operator+=(const std::set<T> &set)
{
typename std::set<T>::iterator itr = set.begin();
for (; itr != set.end(); ++itr)
{
this->data.insert(*itr);
};
return *this;
}
};
template <typename T>
bool set_operations<T>::contains(T search) const
{
bool ret = false;
typename std::set<T>::iterator itr = data.begin();
for (; itr != data.end(); ++itr)
{
if (*itr == search)
{
ret = true;
}
}
return ret;
}
template <typename T>
void set_operations<T>::set_union(std::set<T> set2)
{
typename std::set<T>::iterator itr = set2.begin();
for (; itr != set2.end(); ++itr)
{
data.insert(*itr);
}
}
template <typename T>
bool set_operations<T>::subset(std::set<T> set2) const
{
set_operations<T> test(data);
bool ret = true;
typename std::set<T>::iterator itr = set2.begin();
for (; itr != set2.end(); ++itr)
{
if (!test.contains(*itr))
{
ret = false;
}
}
return ret;
}
template <typename T>
void set_operations<T>::write()
{
typename std::set<T>::iterator itr = data.begin();
for (; itr != data.end(); ++itr)
{
std::cout << *itr << std::endl;
}
};
#endif
i am trying to send a 2d vector by reference but seems like its not working for pretty much same approach
64.minimum-path-sum.cpp: In function ‘int main()’:
64.minimum-path-sum.cpp:67:23: error: cannot bind non-const lvalue reference of type ‘std::vector<std::vector<int> >&’ to an rvalue of type ‘std::vector<std::vector<int> >’
67 | if(minPathSum(vector<vector<int>> 1) == 12)cout << "ACC\n";
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
64.minimum-path-sum.cpp:57:46: note: initializing argument 1 of ‘int minPathSum(std::vector<std::vector<int> >&)’
57 | int minPathSum(vector<vector<int>> & grid) {
|
~~~~~~~~~~~~~~~~~~~~~~^~~~
#include<bits/stdc++.h>
#include "stringTo2dVector.h"
using namespace std;
int main(){
vector<vector<int>> c1;
if(minPathSum(c) == 12)cout << "ACC\n"; //No ERROR
else cout << "WA\n";
if(minPathSum(vector<vector<int>> 1) == 12)cout << "ACC\n"; // ERROR
else cout << "WA\n";
}
What is the difference between these 2 approach of passing a 2d vector as argument ?? What is the difference between these 2 approach of passing a 2d vector as argument ??
samedi 18 décembre 2021
Is there any options to make clang-format produce the following effect?
I use clang-format to format the following code, but the effect is not what I want:
void f(int, int, std::vector<int>, std::map<int, int>)
{}
int main()
{
f(
{
},
{}, {1, 2, 3},
{
{1, 2},
{3, 4},
});
}
Is there any options to make clang-format produce the following effect?
void f(int, int, std::vector<int>, std::map<int, int>)
{}
int main()
{
f({},
{},
{1, 2, 3},
{
{1, 2},
{3, 4},
});
}
Understanding C++ memory orders
While trying to understand memory orders I stumbled upon this video. The video claims that the assertion at the end of the main function may fail, but I do not understand why or if this is correct.
What I understand from std::memory_order_release
is that no reads or writes in the current thread can be re-ordererd after this store. And for std::memory_order_acquire
no reads or writes in the current thread can be re-ordered before this load. But for each reading thread in the example given there is a wait for a different writer thread, and the if
from a reading thread cannot be re-ordered before the while
, because of the std::memory_order_acquire
. So, shouldn't at least one thread increment the z
variable?
#include <atomic>
#include <thread>
#include <memory>
#include <cassert>
std::atomic<bool> x;
std::atomic<bool> y;
std::atomic<int> z;
void write_x() {
x.store(true, std::memory_order_release);
}
void write_y() {
y.store(true, std::memory_order_release);
}
void read_x_then_y() {
while (!x.load(std::memory_order_acquire));
if (y.load(std::memory_order_acquire)) {
z++;
}
}
void read_y_then_x() {
while (!y.load(std::memory_order_acquire));
if (x.load(std::memory_order_acquire)) {
z++;
}
}
int main() {
x = false;
y = false;
z = 0;
std::thread a(write_x);
std::thread b(write_y);
std::thread c(read_x_then_y);
std::thread d(read_y_then_x);
a.join();
b.join();
c.join();
d.join();
assert(z != 0);
return 0;
}
Compiled with CPPFLAGS="-latomic -pthread" make main
How to properly link Boost Library along with configuration file in CMake
I was making an example program based on Boost Program Option Library. I am also using a configuration header file to pass version number to main code. Here is my main.cpp file content:
#include <boost/program_options.hpp>
#include <iostream>
#include "ver.h"
using namespace boost::program_options;
int main(int argc, const char *argv[])
{
try
{
options_description desc{"Options"};
desc.add_options()("help,h", "Help screen")("pi", value<float>()->default_value(3.14f), "Pi")("age", value<int>(), "Age")("version,v", "Version");
variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if (vm.count("help"))
std::cout << desc << std::endl;
else if (vm.count("age"))
std::cout << "Age: " << vm["age"].as<int>() << std::endl;
else if (vm.count("pi"))
std::cout << "Pi: " << vm["pi"].as<float>() << std::endl;
else if (vm.count("version"))
std::cout << "Version: " << ver << std::endl;
}
catch (const error &ex)
{
std::cerr << ex.what() << std::endl;
}
}
This is the content of ver.h.in file:
#pragma once
const char *ver = "${BoostProgOpts_VERSION}"
This is the content of CMakeLists.txt file:
cmake_minimum_required(VERSION 3.10)
project("BoostProgOpts")
set(BoostProgOpts_VERSION_MAJOR 0)
set(BoostProgOpts_VERSION_MINOR 1)
set(BoostProgOpts_VERSION_PATCH 1)
set(BoostProgOpts_VERSION "${BoostProgOpts_VERSION_MAJOR}.${BoostProgOpts_VERSION_MINOR}.${BoostProgOpts_VERSION_PATCH}")
find_package(Boost REQUIRED COMPONENTS program_options)
if(Boost_FOUND)
message("Boost Library Found!")
else()
message("Boost Library Not Found!")
endif()
configure_file(ver.h.in ${PROJECT_BINARY_DIR}/ver.h)
add_executable(binary main.cpp)
include_directories(${CMAKE_BINARY_DIR} ${Boost_INCLUDE_DIRS})
target_link_libraries(binary ${Boost_LIBRARIES})
But while compiling Boost Library is not linking properly. The error showing is:
[main] Building folder: ProgramOptions
[build] Starting build
[proc] Executing command: /usr/bin/cmake --build /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/build --config Debug --target all -j 10 --
[build] Consolidate compiler generated dependencies of target binary
[build] [ 50%] Building CXX object CMakeFiles/binary.dir/main.cpp.o
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:6:1: error: expected ‘,’ or ‘;’ before ‘using’
[build] 6 | using namespace boost::program_options;
[build] | ^~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp: In function ‘int main(int, const char**)’:
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:12:9: error: ‘options_description’ was not declared in this scope; did you mean ‘boost::program_options::options_description’?
[build] 12 | options_description desc{"Options"};
[build] | ^~~~~~~~~~~~~~~~~~~
[build] | boost::program_options::options_description
[build] In file included from /usr/include/boost/program_options.hpp:15,
[build] from /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:1:
[build] /usr/include/boost/program_options/options_description.hpp:191:38: note: ‘boost::program_options::options_description’ declared here
[build] 191 | class BOOST_PROGRAM_OPTIONS_DECL options_description {
[build] | ^~~~~~~~~~~~~~~~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:13:9: error: ‘desc’ was not declared in this scope
[build] 13 | desc.add_options()("help,h", "Help screen")("pi", value<float>()->default_value(3.14f), "Pi")("age", value<int>(), "Age")("version,v", "Version");
[build] | ^~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:13:59: error: ‘value’ was not declared in this scope; did you mean ‘boost::program_options::value’?
[build] 13 | desc.add_options()("help,h", "Help screen")("pi", value<float>()->default_value(3.14f), "Pi")("age", value<int>(), "Age")("version,v", "Version");
[build] | ^~~~~
[build] | boost::program_options::value
[build] In file included from /usr/include/boost/program_options/value_semantic.hpp:421,
[build] from /usr/include/boost/program_options/options_description.hpp:13,
[build] from /usr/include/boost/program_options.hpp:15,
[build] from /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:1:
[build] /usr/include/boost/program_options/detail/value_semantic.hpp:197:5: note: ‘boost::program_options::value’ declared here
[build] 197 | value(T* v)
[build] | ^~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:13:65: error: expected primary-expression before ‘float’
[build] 13 | desc.add_options()("help,h", "Help screen")("pi", value<float>()->default_value(3.14f), "Pi")("age", value<int>(), "Age")("version,v", "Version");
[build] | ^~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:13:116: error: expected primary-expression before ‘int’
[build] 13 | desc.add_options()("help,h", "Help screen")("pi", value<float>()->default_value(3.14f), "Pi")("age", value<int>(), "Age")("version,v", "Version");
[build] | ^~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:15:9: error: ‘variables_map’ was not declared in this scope; did you mean ‘boost::program_options::variables_map’?
[build] 15 | variables_map vm;
[build] | ^~~~~~~~~~~~~
[build] | boost::program_options::variables_map
[build] In file included from /usr/include/boost/program_options.hpp:18,
[build] from /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:1:
[build] /usr/include/boost/program_options/variables_map.hpp:146:38: note: ‘boost::program_options::variables_map’ declared here
[build] 146 | class BOOST_PROGRAM_OPTIONS_DECL variables_map : public abstract_variables_map,
[build] | ^~~~~~~~~~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:16:15: error: ‘parse_command_line’ was not declared in this scope; did you mean ‘boost::program_options::parse_command_line’?
[build] 16 | store(parse_command_line(argc, argv, desc), vm);
[build] | ^~~~~~~~~~~~~~~~~~
[build] | boost::program_options::parse_command_line
[build] In file included from /usr/include/boost/program_options/parsers.hpp:295,
[build] from /usr/include/boost/program_options.hpp:17,
[build] from /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:1:
[build] /usr/include/boost/program_options/detail/parsers.hpp:103:5: note: ‘boost::program_options::parse_command_line’ declared here
[build] 103 | parse_command_line(int argc, const charT* const argv[],
[build] | ^~~~~~~~~~~~~~~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:16:53: error: ‘vm’ was not declared in this scope; did you mean ‘tm’?
[build] 16 | store(parse_command_line(argc, argv, desc), vm);
[build] | ^~
[build] | tm
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:16:9: error: ‘store’ was not declared in this scope; did you mean ‘boost::program_options::store’?
[build] 16 | store(parse_command_line(argc, argv, desc), vm);
[build] | ^~~~~
[build] | boost::program_options::store
[build] In file included from /usr/include/boost/program_options.hpp:18,
[build] from /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:1:
[build] /usr/include/boost/program_options/variables_map.hpp:48:10: note: ‘boost::program_options::store’ declared here
[build] 48 | void store(const basic_parsed_options<wchar_t>& options,
[build] | ^~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:17:9: error: ‘notify’ was not declared in this scope; did you mean ‘boost::program_options::notify’?
[build] 17 | notify(vm);
[build] | ^~~~~~
[build] | boost::program_options::notify
[build] In file included from /usr/include/boost/program_options.hpp:18,
[build] from /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:1:
[build] /usr/include/boost/program_options/variables_map.hpp:53:37: note: ‘boost::program_options::notify’ declared here
[build] 53 | BOOST_PROGRAM_OPTIONS_DECL void notify(variables_map& m);
[build] | ^~~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:22:50: error: expected primary-expression before ‘int’
[build] 22 | std::cout << "Age: " << vm["age"].as<int>() << std::endl;
[build] | ^~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:24:48: error: expected primary-expression before ‘float’
[build] 24 | std::cout << "Pi: " << vm["pi"].as<float>() << std::endl;
[build] | ^~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:28:18: error: ISO C++ forbids declaration of ‘error’ with no type [-fpermissive]
[build] 28 | catch (const error &ex)
[build] | ^~~~~
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:28:23: error: expected ‘)’ before ‘&’ token
[build] 28 | catch (const error &ex)
[build] | ~ ^~
[build] | )
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:28:24: error: expected ‘{’ before ‘&’ token
[build] 28 | catch (const error &ex)
[build] | ^
[build] /home/omecamtiv/WorkPlace/BoostLibExamples/ProgramOptions/main.cpp:28:25: error: ‘ex’ was not declared in this scope; did you mean ‘exp’?
[build] 28 | catch (const error &ex)
[build] | ^~
[build] | exp
[build] make[2]: *** [CMakeFiles/binary.dir/build.make:76: CMakeFiles/binary.dir/main.cpp.o] Error 1
[build] make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/binary.dir/all] Error 2
[build] make: *** [Makefile:91: all] Error 2
[build] Build finished with exit code 2
Please help me regarding this.
C++ Pointers and Destructors
class Dummy
{
public:
int* A{};
int num{};
public:
Dummy(int num)
{
this->num = num;
A = new int[num];
}
~Dummy()
{
delete[] A;
}
};
Dummy* dummy()
{
Dummy* d = new Dummy{ 4 };
d->A[0] = 1;
d->A[1] = 2;
d->A[2] = 3;
d->A[3] = 4;
return d;
}
int main()
{
Dummy* ATT = dummy();
}
When I tired to run this program This is always showing Expection at destructor and program can't continue further. What's wrong in this Code...
vendredi 17 décembre 2021
Trying to understand cause of increased compile time going from C++11 to C++14
Migrating from C++11 to C++14, I have a source file that usually compiles in ~20s in C++11 mode, but when compiling the same file in C++14 mode the compile time increase to ~340s. That's an increase of about 17 times. The size of the generated object code doubles.
So the clarify my question, I'm trying to understand both what in the code and why the compilers takes that much longer for the same code by changing the -std=c++11/c++14
flag for g++
.
To make a fair comparison ran the pre-processor over the code (in C++11 mode) and compiled the output with both the C++11 and C++14 flags. E.g.,
g++ -E -std=c++11 -g -O2 -o spaghetti.E spaghetti.cpp
g++ -c -std=c++11 -g -O2 -o spaghetti-11.o -x c++ spaghetti.E
g++ -c -std=c++14 -g -O2 -o spaghetti-14.o -x c++ spaghetti.E
The file in question does have lots of fixed size arrays of objects in template form like
template<typename T, std::size_t N>
struct Object {
std::array<T,N> storage{};
std::vector<T> counters;
};
Symbols involving Object
do double when compiled with C++14 over C++11 (among others).
So, what motivates the compiler to take 17 times longer to compile the same file? And what should change to reduce this?
I should note that if I change the Object
implementation
template<typename T, std::size_t N>
struct Object {
std::vector<T> storage{}; // was std::array above, N used in other members
std::vector<T> counters;
};
It will compile quickly under both C++11 and C++14.
jeudi 16 décembre 2021
Compare two unsorted std::vector
What is the best way to compare two unsorted std::vector
std::vector<int> v1 = {1, 2, 3, 4, 5};
std::vector<int> v2 = {2, 3, 4, 5, 1};
What I am currently doing is
const auto is_similar = v1.size() == v2.size() && std::is_permutation(v1.begin(), v1.end(), v2.begin());
Here two vectors are similar only when the size of both vectors are equal and they contain the same elements
What would be a better approach for
- two small std::vectors (size well under 50 elements)
- two large std::vectors
print char of words in CUDA kernal
I have passed a char array to the Cuda kernel. Essentially the variable "sites" contains sentences organized into an array format. To check if it has been copied and to identify how to access them in the kernel I tried printing them using the following code.
__global__ void cuda_theta_L(float N, char **sites, int num_Segregrating_sites)
{
int tid = threadIdx.x + blockIdx.x * blockDim.x;
while (tid < num_Segregrating_sites)
{
printf("%d\n", tid);
printf("%s \n", sites[tid]);
tid += blockDim.x * gridDim.x;
}
}
However, it does not print the text. The Cuda error is "kernel launch failed with error "an illegal memory access was encountered"."
I am new to CUDA programming, so a detailed explanation would be greatly appreciated.
How to make the conversion from 'int' to 'char' reasonable under -Werror=conversion option? c++11
error: conversion from ‘int’ to ‘char’ may change value [-Werror=conversion]
build cmd example: g++ -std=c++11 test.cpp -o a.out -Werror=conversion
auto index = 3;
char singleChar = 'A' + index; // I want to get A-Z
I hope sigleChar is dynamically assigned. could you pls help me to solve this error report without using switch? How would it be better to write code?
mercredi 15 décembre 2021
module machine type 'X86' conflicts with target machine type 'x64' error in boost_date_time-vc140-mt-gd-1_59.dll
When i try to compile my visual studio project getting this error.
module machine type 'X86' conflicts with target machine type 'x64' error in boost_date_time-vc140-mt-gd-1_59.dll
I am using visual studio community 2015.
shill script for C++ in linux
I have a C++ code and I need to run it 2000 times and print the results of all runs in a text file or data file. I can run it from the terminal by:
- g++ -o program_name program_name.cpp
- ./program_name
How to get all values in SQL from a table's column, in QT C++
So I'm trying to get all of the values from a sqlite3 database in QT with C++ (11). My table called "Auteurs", and the column that contains all the values called "nom".
With DB Browser I successfully extracted all the values but implementing it into my program that accepted the the following syntax :
Etudiants->exec(QLatin1String("SELECT nom FROM Auteurs WHERE nom is not NULL"));
without any error specification after compiling and executing the program tells me that it crashed. Any idea why it does ? and in what sort of type I should store the values, that I will get (QStringList)?
Other useful indications : Qt 5.14.1 (i386-little_endian-ilp32 shared (dynamic) release build; by MSVC 2017) on "windows" OS: Windows 8.1 Version 6.3 (Build 9600) [winnt version 6.3.9600]
Architecture: x86_64; features: SSE2 SSE3 SSSE3 SSE4.1 SSE4.2 AVX AVX2
Thank you for your help !
error: no matching function for call to ‘recherche(std::vector >&, std::vector >::iterator, std::vector >::iterator, const char [10])’
i got this error : error: no matching function for call to ‘recherche(std::vector >&, std::vector >::iterator, std::vector >::iterator, const char [10])’
error: no matching function for call to ‘recherche(std::__cxx11::list&, std::__cxx11::list::iterator, std::__cxx11::list::iterator, int)’
error: no matching function for call to ‘recherche(std::array&, std::array::iterator, std::array::iterator, double)’
#include<iostream>
#include<vector>
#include<array>
#include<list>
#include<algorithm>
#include<iterator>
#include<set>
using namespace std;
template <template<typename> class C, class InputIterator, typename A>
bool recherche(C<A> s, InputIterator debut, InputIterator fin, A n)
{
InputIterator itr;
for (itr = debut; itr != fin; itr++) {
if(*itr == n){
return 1;
}}
return 0;
}
int main(){
vector<string> strVec = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
list<int> my_list = { 12, 5, 10, 9, 4, 90 };
array<float, 5> arr = { 10.56, 20.99, 30.34, 40.12, 10.1 };
cout << recherche(strVec, strVec.begin(), strVec.end(), "Wednesday") << endl;
cout << recherche(my_list, my_list.begin(), my_list.end(), 90) << endl;
cout << recherche(arr, arr.begin(), arr.end(), 30.34) << endl;
return 0;
}
}
Can we use an executable file as shared library on all platforms(Windows, Mac, Linux)?
On some linux systems this works. Can I generally design plugin based apps such that there is no library, but only header files and the executable?
Afaik this always works if the interface classes are interfaces in the sense that they only contain pure virtual functions. But can I also define classes in the interface containing symbols that have to be bound by linking against an executable containing them?
Use case: an executable foo, the app, offers plugins an interface through a shared library libfoo. Plugins (shared libs) are loaded at runtime. Both, the app and plugins, link against libfoo to resolve symbols in the classes both of them use. Is this necessary or can put the classes in the executable target and let the plugins link the executable instead?
While I was learning Inheritance in C++ 17...I came to an error as shown.. [ Error: non-standard syntax; use '&' to create a pointer to member ]
Error : after I tried to run my project
Elaboration: Was trying to learn Inheritance ,by deriving a "Savings Account" class from the parent class => "Account" class. But now I am stuck. Error: non-standard syntax; use '&' to create a pointer to member
main.cpp
#include <iostream>
#include <string>
#include "Account.h"
#include "Savings_Account.h"
using namespace std;
int main() {
cout << "\nAccount=======================" << endl;
Account acc{};
acc.deposit(2000.0);
acc.withdraw(500.0);
cout << endl;
Account* p_acc{ nullptr };
p_acc = new Account();
p_acc->deposit(1000.0);
p_acc->withdraw(500.0);
delete p_acc;
cout << "\nSavings_Account===============" << endl;
Savings_Account sav_acc{};
sav_acc.deposit(2000.0);
sav_acc.withdraw(500.0);
cout << endl;
Savings_Account* p_sav_acc{ nullptr };
p_sav_acc = new Savings_Account();
p_sav_acc->deposit(1000);
p_sav_acc->withdraw(500.0);
delete p_sav_acc;
return 0;
}
Account.h
#ifndef _ACCOUNT_H_
#define _ACCOUNT_H_
#include <iostream>
#include <string>
using namespace std;
class Account {
public:
double balance;
string name;
void deposit(double amount);
void withdraw(double amount);
Account();
~Account();
};
#endif
Account.cpp
#define _CRT_SECURE_NO_WANINGS
#include "Account.h"
Account::Account()
: balance{ 0 }, name{ "NULL" }{
}
Account::~Account() {
}
void Account::deposit(double amount) {
cout << "Account deposit was " << amount << endl;
}
void Account::withdraw(double amount) {
cout << "Account withdraw was " << amount << endl;
}
Savings_Account.h
#ifndef _SAVINGS_ACCOUNT_H_
#define _SAVINGS_ACCOUNT_H_
#include <iostream>
#include <string>
#include "Account.h"
class Savings_Account : public Account {
public:
double interest_rate;
Savings_Account();
~Savings_Account();
void deposit(double amount);
void withdraw(double amount);
};
#endif
Savings_Account.cpp
#define _CRT_SECURE_NO_WANINGS
#include "Savings_Account.h"
Savings_Account::Savings_Account()
:interest_rate{ 3.0 } {
}
Savings_Account::~Savings_Account() {
}
void Savings_Account::deposit(double amount) {
cout << "Savings Account deposited " << deposit << endl;
}
void Savings_Account::withdraw(double amount) {
cout << "Savings Account withdraw " << withdraw << endl;
}
Note : Using Visual Studio-2022 IDE.
Boost Serialization Library in MEX
I am trying to convert my MEX/MATLAB/C++ program into solely C++. And the first big step is getting rid of saving files as mat file. I am saving various structs so from my understanding serialization is going to be involved. Boost looks to be the most easy to implement (to me anyway) but I am having trouble compiling. I found example code from codeguru and tried to implement that into a simple MEX function:
#include <fstream>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include "mex.h"
using namespace std;
class Employee {
private:
friend class boost::serialization::access;
int id;
string name;
float salary;
template<class Archive>
void serialize(Archive &a, const unsigned version){
a & id & name & salary;
}
public:
Employee(){}
Employee(int i, string n, float s):id(i),name(n),salary(s)
{}
};
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
const string filename = "emp.dat";
Employee e1(11,"Harry",4500.00f);
Employee e2(22,"Ravi",8800.00f);
Employee e3(33,"Tim",6800.00f);
Employee e4(44,"Rajiv",3400.00f);
// Serialize and persist the object
{
std::ofstream outfile(filename);
boost::archive::text_oarchive archive(outfile);
archive << e1 << e2 << e3 << e4;
}
}
When I try to compile I use:
mex -v COMPFLAGS='$COMPFLAGS /std:c++11' COPTIMFLAGS="-O3 -fwrapv -DNDEBUG" CFLAGS="$CFLAGS -fopenmp -march=native" -IC/boost_1_78_0 read_testing.cpp
And I get a long list of errors. The first few lines are:
Error using mex
/usr/bin/ld: /tmp/mex_30338390276068_4258/read_testing.o: in function `mexFunction':
read_testing.cpp:(.text+0x332): undefined reference to
`boost::archive::text_oarchive_impl<boost::archive::text_oarchive>::text_oarchive_impl(std::ostream&,
unsigned int)'
I've never had to use boost before so there is a good chance I am missing something simple. It does compile if I comment out the serialization section at the end. Any help would be greatly appreciated.
Please solve and explain BEST INDEX Question of HackerEarth Question and explain the code described below in C++ language
This is the following C++ Hackerearth Question, which I found a solution but couldn't understand it.
Here's the Question:
CODE:
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int n;
cin >> n;
long a[n];
for(int i=0;i<n;i++) {
cin>>a[i];
a[i]+=a[i-1];
}
long max=a[n-1]-a[n-2];
for(int i=1;i<n-1;i++) {
int k;
k = (-1+sqrt(1+8*(n-i)))/2;
k = (k*(k+1))/2;
if((a[k+i-1]-a[i-1])>max) {
max=a[k+i-1]-a[i-1];
}
}
cout<<max;
}
So in this Question can you please explain the logic behind this code? I'm a beginner in programming.
- k = (-1+sqrt(1+8*(n-i)))/2; k = (k*(k+1))/2; How did these 2 expressions come into picture? logic behind this.
- If loop explanation?
mardi 14 décembre 2021
Is it a good practice to have a use a template in a derived class? C++ 11
I am currently new to C++ in the working world (learnt C++ academically). This is my first job where C++ is the base requirement.
May I ask -
- When do I use a template for a class?
- Is there any ideal or good practices that uses a template in a derived class, where the base class does not inherit any templates?
For example:
class Base {};
<typename T>
class Derived : public Base {};
The reason why I need to inherit from a base is because I need to store objects where it can be referenced from the base, and thereafter have a common factory method where I can pull information out.
C++ trait for "has no constructors" OR trait for "is zero-initializable"?
cppreference says for zero initialization:
Zero initialization is performed in the following situations: ... 2) As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, ...
What trait or combination of traits can I use to test either for:
- type is zero-initializable with an empty
{}
, or - class type has "no constructors"
- (which I think means no user-defined constructors?)
(P.S. tagged C++11
to indicate any "modern C++" approach is acceptable; also tagged C++17
to indicate the latest C++ version I'd like for an answer.)
(P.P.S. I know cppreference is not the standard, but it is almost always correct. If it is not correct in this case, that should be part of the answer ...)
Why template function with 'const' from left of parameter type is misbehaving against the rule of type deduction for pointer argument?
Consider this pseudo code for a type deduction case:
template<typename T> void f(ParamType param);
Call to function will be:f(expr);
According to type deduction case where ParamType is not a reference, pointer, nor a universal reference (see S. Meyers "Effective Modern C++", p.14), but passed by value, to determine type T, one needs firstly to ignore the reference and const part of 'expr' and then pattern-match exprs type to determine T.
The driver will be:
void PerformTest() {
int i = 42;
int* pI = &i;
f_const_left(pI);
f_non_template_left(pI);
f_const_right(pI);
f_non_template_right(pI);
}
Now consider these functions, which, using this deduction rule, are showing some counter-intuitive results while being called with pointer as an argument:
template<typename T> void f_const_left(const T t) {
// If 'expr' is 'int *' then, according to deduction rule for value parameter (Meyers p. 14),
// we need to get rid of '&' and 'const' in exp (if they exist) to determine T, thus T will be 'int *'.
// Hence, ParamType will be 'const int *'.
// From this it follows that:
// 1. This function is equivalent to function 'func(const int * t){}'
// 2. If ParamType is 'const int *' then we have non-const pointer to a const object,
// which means that we can change what pointer points to but cant change the value
// of pointer address using operator '*'
*t = 123;// compiler shows no error which is contradiction to ParamType being 'const int *'
t = nullptr; // compiler shows error that we cant assign to a variable that is const
// As we see, consequence 2. is not satisfied:
// T is straight opposite: instead of being 'const int *'
// T is 'int const *'.
// So, the question is:
// Why T is not 'const int*' if template function is f(const T t) for expr 'int *' ?
}
Consider consequence 1.:
Lets create an equivalent non-template function:
void f_non_template_left(const int* t) {
// 1. Can we change the value through pointer?
*t = 123; // ERROR: expression must be a modifiable lvalue
// 2. Can we change what pointers points to?
t = nullptr; // NO ERROR
// As we can see, with non-template function situation is quite opposite.
}
For for completeness of the experiment, lets also consider another pair of functions but with 'const' being placed from the right side of a T: one template function and its non-template equivalent:
template<typename T> void f_const_right(T const t) {
// For expr being 'int *' T will be 'int *' and ParamType will be 'int * const',
// which is definition of a constant pointer, which cant point to another address,
// but can be used to change value through '*' operator.
// Lets check it:
// Cant point to another address:
t = nullptr; // compiler shows error that we cant assign to a variable that is const
// Can be used to change its value:
*t = 123;
// So, as we see, in case of 'T const t' we get 'int * const' which is constant pointer, which
// is intuitive.
}
Finally, the non-template function with 'const' from the right side of type:
void f_non_template_right(int* const t) {
// 1. Can we change the value through pointer?
*t = 123; // No errors
// 2. Can we change what pointers points to?
t = nullptr; // ERROR: you cant assign to a variable that is const
// As we can see, this non-template function is equivalent to its template prototype
}
Can someone explain why there is such insonsistency between template and non-template functions ? And why template function with 'const' on the left is behaving not according to the rule of deduction?
how to fill a doubly linked list from input file text
The structure
Company
is a doubly linked list of all the employees. Write a function that parses the input text file and returns the doubly linked list of all the employees in your input text file. This function should pay particular attention to correctly build the ‘Calendar’ and the ‘List of Attendees’ for each scheduled appointment.
struct Employee {
int UniqueID;
char FirstName[30], LastName[30], EmailAddress[50];
Attendee *myAtt;
Employee *next;
Employee *previous;
};
struct Attendee {
Employee *self;
Attendee *next;
};
struct Company {
Employee *Head, *Tail;
};
struct Time {
int Day, Hour, Minute, Second;
};
struct Appointment {
char Title[50];
Time StartingTime;
int Duration;
Attendee *ListOfAttendees;
Appointment *next;
};
Employee* push(struct Employee* head, struct Employee* node1, struct Employee* node2) {
struct Attendee* a1 = new Attendee;
struct Attendee* a2 = new Attendee;
struct Employee* temp1 = node1;
struct Employee* temp2 = node2;
struct Attendee* p = new Attendee;
struct Attendee* p1 = new Attendee;
Company* c;
if (head == NULL)
{
a1->self = node2;
a1->next = NULL;
node1->myAtt = a1;
node1->previous = NULL;
node1->next = node2;
node2->next = NULL;
node2->previous = node1;
a2->self = node1;
a2->next = NULL;
head = node1;
}
else
{
int counteratt1 = 0;
Employee* em = head;
int counteratt2 = 0;
while (em->next != NULL)
{
if (em->FirstName == node1->FirstName && em->LastName == node1->LastName) {
counteratt1++;
}
if (em->FirstName == node2->FirstName && em->LastName == node2->LastName) {
counteratt2++;
}
em = em->next;
}
if (counteratt1 == 0)
{
a1->self = node2;
a1->next = NULL;
node1->myAtt = a1;
node1->next = head;
node1->previous = NULL;
head->previous = node1;
head = node1;
}
if (counteratt2 == 0)
{
a2->self = node1;
a2->next = NULL;
node2->next = head;
node2->myAtt = a2;
node2->previous = NULL;
head->previous = node2;
head = node2;
head->myAtt->next = NULL;
}
else
{
struct Employee* k = head;
while (k != NULL)
{
if (k->FirstName == node1->FirstName && k->LastName == node1->LastName)
{
p = k->myAtt;
a1->self = node2;
while (p->next != NULL) {
p = p->next;
}
p->next = a1;
a1->next = NULL;
}
if (k->FirstName == node2->FirstName && k->LastName == node2->LastName)
{
p1 = k->myAtt;
a2->self = node1;
while (p1->next != NULL) {
p1 = p1->next;
}
p1->next = a2;
a2->next = NULL;
}
k = k->next;
//
}
}
}
return head;
}
Does this code cause data race condition?
I'm writing multi thread code on x64 windows msvc.
I don't want to use std::atomic because it flush write combined buffer.
static unsigned int value[100];
thread1
for(size_t i = 0 ; i < 100 ; i++)
{
if( (value[i] & (1 << 1)) != 0 )
{
value[i] |= (1 << 2);
}
}
thread2
for(size_t i = 0 ; i < 100 ; i++)
{
if( (value[i] & (1 << 1)) != 0 )
{
value[i] |= (1 << 2);
}
}
Error Reading a return of a function from main
I have the following function which reads the header of specific .WAV files using RIFF fmt.
WORD CWav::Read_Header(FILE* WAVF) {
//Checking For PCM TRUE/FALSE
fseek(WAVF, 48, SEEK_SET);
int16_t num_bytes_in_ext;
fread(&num_bytes_in_ext, sizeof int16_t, 1, WAVF);
if (num_bytes_in_ext == 0)
{
PCM = true;
}
else if (num_bytes_in_ext != 0) PCM = false;
if (PCM == false) {
fread(&FCD, 1, sizeof(FMT_CHUNCK_DISCRIPTOR), WAVF);
}
else if (PCM == true) fread(&FCD_PCM, 1, sizeof(FMT_CHUNCK_DISCRIPTOR_PCM), WAVF);
char FMT[5] = "fmt ";
if (PCM == false && memcmp(FCD.fmt, FMT, sizeof(FCD.fmt)) != 0 || PCM == true && memcmp(FCD_PCM.fmt, FMT, sizeof(FCD_PCM.fmt)) != 0) {
fseek(WAVF, 24, SEEK_SET);
fread(&FCD_PCM, 1, sizeof(FMT_CHUNCK_DISCRIPTOR_PCM), WAVF);
fread(&FCD, 1, sizeof(FMT_CHUNCK_DISCRIPTOR), WAVF);
if (PCM != true) {
while (memcmp(FCD.fmt, FMT, sizeof(FCD.fmt)) != 0) {
fseek(WAVF, FCDSeek++, SEEK_CUR);
fread(&FCD, 1, sizeof(FMT_CHUNCK_DISCRIPTOR_PCM), WAVF);
}
}
else {
while (memcmp(FCD_PCM.fmt, FMT, sizeof(FCD_PCM.fmt)) != 0) {
fseek(WAVF, FCDSeek++, SEEK_CUR);
fread(&FCD_PCM, 1, sizeof(FMT_CHUNCK_DISCRIPTOR_PCM), WAVF);
}
}
if (PCM == false) {
BUFFER_SIZE = DSC.Subchunk2Size / (FCD.NumOfChan * (FCD.bitsPerSample / 8));
SampelsPerSec = FCD.SamplesPerSec;
}
else {
BUFFER_SIZE = DSC.Subchunk2Size / (FCD_PCM.NumOfChan * (FCD_PCM.bitsPerSample / 8));
SampelsPerSec = FCD_PCM.SamplesPerSec;
}
return BUFFER_SIZE;
}
}
Using the debugger I saw that BUFFER_SIZE
was assigned the value 2612
However whenever I call the function Read header from main I never get a return
main.cpp
Wavptr->Read_Header(InFile);
WORD BUFFER_SIZE = Wavptr->Read_Header(InFile);