I want the output to be: 1 2 2 2
But why is the output: 1 2 3 4
What's wrong with this code?
#include <iostream>
using namespace std;
int arr[] = {0};
int pluss(int ar[],int a){
ar[0]++;
cout<<ar[0]<<endl;
if(a==0){
pluss(ar,a+1);
pluss(ar,a+1);
pluss(ar,a+1);
}
}
int main() {
pluss(arr,0);
return 0;
}
EDIT: So, the "ar" is global and not local to one child function? how to make it so the "ar" is only local to one child function? I mean: the "ar" in the first pluss(ar,1) is different from the "ar" in the second pluss(ar,2)?
Your code is equivalent of :
int main() {
pluss(arr,0);
pluss(arr,1);
pluss(arr,1);
pluss(arr,1);
return 0;
}
Since each call to pluss definitely increments the array element, before printing it, expected output is 1, 2, 3, 4.
how to make it so the "ar" is only local to one child function?
If you don't like to pass each array element as integer value, you could wrap the array in a struct, since structures are passed by value rather than by reference.
#include <iostream>
using namespace std;
struct s { int a[1]; } arr = {0};
int pluss(struct s ar, int a)
{
ar.a[0]++;
cout <<ar.a[0] <<endl;
if (a==0)
{
pluss(ar, a+1);
pluss(ar, a+1);
pluss(ar, a+1);
}
}
int main()
{
pluss(arr, 0);
return 0;
}
Related
I created a class "config" that contains 12 bool values, organized in a std::array. The class has an "icing" function that returns a double value.
Trying to order a vector of 2^12 (4096) configs through a std:: sort (contained in #include ) using a predicate i have written, i get a segmentation fault error.
Shrinking the vector to 205 (not 1 more) eliminates the error, but I don't know why.
If i make the vector 4096 long, and try to sort only a little part, it works until the part is long 175+.
Shrinking the vector to for example around 1000, limits the partial sorting to around 20, before it gives the segmentation error.
#include <array>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class config {
public:
config (){ //constructor, default
array<bool,12> t;
for (bool& b: t){
b=false;
}
val=t;
g=1;
}
config (const config& fro): val(fro.val){}; //copy constructor
array<bool,12> get_val(){ return val; } //returns the array
void set_tf(int n, bool tf){ val[n]=tf; } //sets a certain boolean in the array to false/true
void set_g(double d){ g=d; } //this sets the constant for calculation to a number
void print(){
cout<<"values: ";
for (auto b: val){ cout<<b<<" "; }
cout<<endl;
}
config & incr(int n=1){ //this increases the vector by 1 following the rules for binary numbers, but has the digits reversed
for(int j=0; j<n; j++){
int i=0;
bool out=false;
while(val[i]==true){
val[i]=false;
i++;
}
val[i]=true;
}
return *this;
}
double energy(){
int ct=0;
int cf=0;
for(auto b:val){ if(b==true){ ct++; } else { cf++; } }
return (abs(ct-cf));
}
double icing(){ //here is the "value" for ordering purposes
int n=0;
for(int i=0; i<11; i++){
if(val[i]!=val[i+1]){ n++; }
}
double temp=-g*n+this->energy();
return temp;
}
private:
array<bool,12> val;
double g;
};
bool pred (config c1, config c2){ return c1.icing()>c2.icing(); } //this sets the ordering predicate
template <typename T> //this orders the vector
void csort (vector <T>& in){
sort(in.begin(), in.end(), pred);
}
int main(){
vector<config> v;
for (int i=0; i<4096; i++){ //cicle that creates a vector of successive binaries
for(auto& c:v){
c.incr();
}
config t;
v.push_back(t);
}
sort(v.begin(), v.begin()+174, pred); //this gives seg.fault when 175+
csort(v); //this gives segmentation fault when the vec is 206 long or longer
}
I expected the code to order the vector, but it goes into segmentation fault.
Your program has undefined behaviour in sort function because your predicate takes config by value, so copies are made and in this place copy constructor is called which copies only array val, but not g.
bool pred (config c1, config c2){ return c1.icing()>c2.icing(); }
// takes by value, copy ctor is called
config (const config& fro): val(fro.val){}; // only val is copied, g HAS GARBAGE VALUE
// icing in pred uses g !! - stric weak ordering is violated because g has GARBAGE VALUE
Fix 1:
pass config by const config&:
bool pred (const config& c1, const config& c2){ return c1.icing()>c2.icing(); }
or fix 2:
g is initialized in copy constructor:
config (const config& fro): val(fro.val), g(fro.g){};
I want to create a heap data structure to be able to update the value .
but my simple code below throw an exception. why it gives the following:
109 : 3 terminate called after throwing an instance of 'std::bad_function_call' what(): bad_function_call
#include <set>
#include <algorithm>
#include <functional>
#include <boost/heap/fibonacci_heap.hpp>
int main() {
// Creating & Initializing a map of String & Ints
std::map<int, vector<int> > mapOfWordCount = { { 1000, {0,1,10,8} }, { 10001, {1,5,99} }, { 1008, {7,4,1} } , { 109, {1,5,3} }};
// Declaring the type of Predicate that accepts 2 pairs and return a bool
typedef std::function<bool(std::pair<int, vector<int> > v1, std::pair<int, vector<int> > v2)> Comparator;
// Defining a lambda function to compare two pairs. It will compare two pairs using second field
Comparator compFunctor =
[](std::pair<int, vector<int> > elem1 ,std::pair<int, vector<int> > elem2)
{
return elem1.second.size() > elem2.second.size();
};
boost::heap::fibonacci_heap <std::pair<int, vector<int> >, boost::heap::compare<Comparator> > pq;
typedef boost::heap::fibonacci_heap< std::pair<int, vector<int> >, boost::heap::compare<Comparator> >::handle_type handle_t;
handle_t* tab_handle = new handle_t [mapOfWordCount.size()];
unsigned iter(0);
for( auto& element : mapOfWordCount) {
tab_handle[iter++]=pq.push(element);
std::cout << element.first << " : " << element.second.size() << std::endl;
}
}
std::bad_function_call exception is caused (in this case) when calling a std::function that is empty.
I have made this work by making Comparator a functor.
struct Comparator
{
bool operator()(std::pair<int, std::vector<int> > elem1, std::pair<int, std::vector<int> > elem2) const
{
return elem1.second.size() > elem2.second.size();
}
};
This can then be used in the declarations of pq and handle_t.
Output:
109 : 3
1000 : 4
1008 : 3
10001 : 3
See demo here.
You can figure out how to make it work with a lambda.
Hint: It involves using the lambda compFunctor as an argument for construction.
I need to remove some elements from a vector of strings if any of the strings contain a certain word.
How can I write the unary predicate for remove_if?
Here is code sample:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool remove_if_found(string word)
{
// ???
}
int main()
{
vector<string> data {
{ "the guitar has six strings" },
{ "the violin has four strings" },
{ "the the violin is more difficult to learn" },
{ "saxophones are a family of instruments" },
{ "the drum is a set of percussions" },
{ "the trumpet is a brass" }
};
cout << data.size() << endl; // output: 6
remove_if(data.begin(), data.end(), remove_if_found("violin")); // error
cout << data.size() << endl; // output should be: 4
return 0;
}
The problem is that the expression remove_if_found("violin") returns a bool which cannot be passed to std::remove_if.
The easiest solution for you would be to change remove_if_found as such:
void remove_if_found(vector<string>& vec, const string& word)
{
vec.erase(remove_if(vec.begin(), vec.end(), [&word](const string& el) {
// check if the word is contained within the string
return el.find(word) != std::string::npos;
}), vec.end());
}
which takes a reference to the vector as well as the string to look for and does the removal as normal.
Then in main you just call it as such:
remove_if_found(data, "violin");
The reason for the erase+remove usage in the remove_if_function is important. std::remove_if merely moves the elements you wish to remove to the end of the vector and returns an iterator to the first of those (re)moved elements. On the other hand std::vector::erase takes two iterators - the returned one from std::remove_if iterator and vec.end() and actually erases them from the vector.
This question already has answers here:
error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘std::vector<bool>::reference {aka std::_Bit_reference}’
(2 answers)
Closed 4 years ago.
Why does iterating over a vector of bool ( w/ modifying the element) require the &&, and not the vector of int?
// junk10.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <algorithm>
#include <array>
#include <vector>
using namespace std;
int main()
{
vector<int> miv{ 1, 2, 3 };
for (auto &e : miv) { e = 15; } // Legal
vector<bool> mbv{ false };
for (auto &e : mbv) { e = true; } // Illegal
for (auto &&e : mbv) { e = true; } // Legal
return 0;
}
The way std::vector<bool> is implemented, is that for space efficiency each boolean occupies 1 bit and not 1 byte, as a boolean.
This means you cannot take a reference to it. A reference is a wrapped pointer, and you cannot have a pointer to a bit.
You can use auto && in C++ 11 to modify the bit, but note that auto does not become a boolean:
std::vector<bool> vec { 1, 0, 1 };
bool &&i = vec[1];
i = 1; // DOES NOT MODIFY VECTOR
auto &&k = vec[2];
k = 0; // MODIFIES VECTOR
for (bool i : vec)
std::cout << i;
100
I have successfully designed the algorithm to print all the permutations with the repetition of numbers. But the algorithm which I have designed has a flaw. It works only if the chars of the string are unique.
Can someone help me out in extending the algorithm for the case where chars of the string may not be unique..
My code so far :
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<climits>
#include<iostream>
using namespace std;
void _perm(char *arr, char*result, int index)
{
static int count = 1;
if (index == strlen(arr))
{
cout << count++ << ". " << result << endl;
return;
}
for (int i = 0; i < strlen(arr); i++)
{
result[index] = arr[i];
_perm(arr, result, index + 1);
}
}
int compare(const void *a, const void *b)
{
return (*(char*)a - *(char*)b);
}
void perm(char *arr)
{
int n = strlen(arr);
if (n == 0)
return;
qsort(arr, n, sizeof(char), compare);
char *data = new char[n];
_perm(arr, data, 0);
free(data);
return;
}
int main()
{
char arr[] = "BACD";
perm(arr);
return 0;
}
I am printing the output strings in lexicographically sorted way.
I am referring to the example.3 from this page.
http://www.vitutor.com/statistics/combinatorics/permutations_repetition.html
Thanks.
Your code doesn't print permutations, but four draws from the string pool with repetition. It will produce 4^4 == 256 combinations, one of which is "AAAA".
The code Karnuakar linked to will give you permutations of a string, but without distinguishing between the multiple occurrences of certain letters. You need some means to prevent recursing with the same letter in each recursion step. In C++, this can be done with a set.
The example code below uses a typical C string, but uses the terminating '\0' to detect the end. The C-string functions from <cstring> are not needed. The output will not be sorted unless the original string was sorted.
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
void perm(char *str, int index = 0)
{
std::set<char> used;
char *p = str + index;
char *q = p;
if (*p == '\0') {
std::cout << str << std::endl;
return;
}
while (*q) {
if (used.find(*q) == used.end()) {
std::swap(*p, *q);
perm(str, index + 1);
std::swap(*p, *q);
used.insert(*q);
}
q++;
}
}
int main()
{
char arr[] = "AAABB";
perm(arr);
return 0;
}
This will produce 5! == 120 permutations for "ABCDE", but only 5! / (2! 3!) == 10 unique permutations for "AAABB". It will also create the 1260 permutations from the linked exercise.