Remove all elements from array greater than n - c++

I'm beginner in programming. Something is giving me trouble to code. Suppose, I've an array.
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
I want to remove all elements which are greater than 9. How can I do this?

You can do this if you use vector. First initialize vector with your array. Then use remove_if() function. Hope this will help.
#include <algorithm>
#include <vector>
int main()
{
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
vector<int> V(Array, Array+20);
vector<int> :: iterator it;
it = remove_if(V.begin(), V.end(), bind2nd(greater<int>(), 9));
V.erase (it, V.end()); // This is your required vector if you wish to use vector
}

You cannot remove items from an array, since they are fixed in size.
If you used std::vector, then the solution would look like this:
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
std::vector<int> Array = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
Array.erase(remove_if(Array.begin(), Array.end(), [](int n) { return n > 9; }),
Array.end());
copy(Array.begin(), Array.end(), ostream_iterator<int>(cout, " "));
}
Live example: http://ideone.com/UjdJ5h
If you want to stick with your array, but mark the items that are greater than 10, you can use the same algorithm std::remove_if.
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
int *overwrite_start = remove_if(std::begin(Array), std::end(Array), [](int n){ return n>9; });
fill(overwrite_start, std::end(Array), -1);
copy(std::begin(Array), std::end(Array), ostream_iterator<int>(cout, " "));
}
The above will move the "erased" items to the end of the array, and mark them with -1.
Live example: http://ideone.com/7rwaXy
Note the usage in both examples of the STL algorithm functions. The second example with the array uses the same remove_if algorithm function. The remove_if returns the start of the "erased" data, as remove_if doesn't actually remove, but moves the data to the end of the sequence.

i am try swap concept without using vector
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
int n;
int arr_len = sizeof(Array)/sizeof(int);
void print_array_value() {
int i;
cout << "\n";
for (i = 0; i < arr_len; i++) {
cout << Array[i] << ", ";
}
cout << " : " << arr_len << "\n";
}
void swap_array_value(int start) {
int i;
for ( ; (start+1) < arr_len; start++) {
Array[start] = Array[start+1];
}
}
void remove_array_value() {
int i;
for (i = 0; i < arr_len; i++) {
if (Array[i] > n) {
swap_array_value(i);
arr_len--;
i--;
}
}
}
void main () {
clrscr();
cout << "Enter the N value : ";
cin >> n;
print_array_value();
remove_array_value();
print_array_value();
cout << "Array Length : " << arr_len;
getch();
}

Related

how to array in c++

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<double> numbers(input_number);
cout << "Enter numbers from 0 to 50: " << endl;
for (int i = 0; i < input_number; ++i) {
cin >> numbers[i];
}
unordered_map<int, int> freq;
for (int i = 0; i < numbers.size(); i++) {
freq[numbers[i]]++;
}
for (int i = 0; i < numbers.size(); i++) {
cout << freq[numbers[i]];
}
return 0;
}
When the use inputs numbers, for example 1,1,1,2 the output should be "1" because it is the most frequent number but the output here became "3,3,3,1" How to solve this problem?
You are most of the way there. Your frequencies are all stored, and you just need to search through the unordered_map now to find the item that has the largest value. Since you're already using <algorithm> you can leverage std::max_element to help:
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
int main()
{
std::vector<int> numbers = { 1, 2, 3, 2, 3, 2, 2 };
std::unordered_map<int, int> freq;
for (int n : numbers) ++freq[n];
if (!freq.empty())
{
auto it = std::max_element(freq.begin(), freq.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
std::cout << "Most frequent is " << it->first << "\n";
}
}
Output:
Most frequent is 2
Here, a custom comparison function is supplied that tests only the frequency part of the element (otherwise the default behavior will compare the full key/value pairs which will result in finding the largest number).
Note that because the map is unordered, there won't be a predictable outcome for tie-breakers (where more than one number is the most frequent). If you need to handle that in a more predictable way, you'll need to adjust the comparison function or possibly just loop over the container yourself if it requires additional work.
One option for tie-breaking is to choose the lowest number. That could be achieved by modifying the comparison to:
return std::make_pair(a.second, b.first) < std::make_pair(b.second, a.first);
The problem is that you just output all the values in map. In a naive implementation you have to iterate through map and register the maximum value and it's frequency:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main()
{
using std::cin, std::cout, std::endl;
using std::vector, std::unordered_map;
int input_number = 0, max_freq = 0, max_val = 0;
cout << "How many numbers you want to input: " << endl;
cin >> input_number;
// Making input double may creates questions
vector<int> numbers(input_number);
cout << "Enter numbers from 0 to 50: " << endl;
for (int i = 0; i < input_number; ++i) {
cin >> numbers[i];
}
unordered_map<int, int> freq;
for (int i = 0; i < numbers.size(); i++) {
freq[numbers[i]]++;
}
// iterating over the map and finding max value
for (auto val : freq) {
if( val.second > max_freq) {
max_val = val.first;
max_freq = val.second;
}
}
cout << max_val;
return 0;
}
Standard maps do store values as pairs of key and value (std::pair). This can be done in easier way: you can do that right while inputting the numbers.
for (int i = 0; i < numbers.size(); i++) {
int val = numbers[i];
int curfreq = ++freq[val];
if (curfreq > max_freq) {
max_val = val;
max_freq = curfreq;
}
}
cout << max_val;
Your array freq has to proper values in it. But your logic in the print out is wrong. You are printing the numbers twice. I guess you want to print all the numbers from 0 to 50.
cout << freq[i]
Then you see which entries have values or not. Then add some logic (which doesn't exist in your code) to pick the proper value. Like the biggest count..

C++ How to sum only even values stored in vector?

I am new to C++, and I have run into a total lack of understanding on how to sum only even values stored in a vector in C++.
The task itself requests a user to input some amount of random integers, stop when input is 0, and then to return the amount of even values and the sum of those even values.
This is as far as I have managed to get:
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
vector<int> vet;
int s = 1;
while (s != 0) {
std::cin >> s;
vet.push_back(s);
}
int n = count_if(vet.begin(), vet.end(),
[](int n) { return (n % 2) == 0; });
cout << n << endl;
//here is the start of my problems and lack of undertanding. Basically bad improv from previous method
int m = accumulate(vet.begin(), vet.end(), 0,
[](int m) { for (auto m : vet) {
return (m % 2) == 0; });
cout << m << endl; //would love to see the sum of even values here
return 0;
}
The function to be passed to std::accumulate takes 2 values: current accumulation value and value of current element.
What you should do is add the value if it is even and make no change when not.
int m = accumulate(vet.begin(), vet.end(), 0,
[](int cur, int m) {
if ((m % 2) == 0) {
return cur + m; // add this element
} else {
return cur; // make no change
}
});
From c++20, you can separate out the logic that checks for even numbers, and the logic for summing up those values:
auto is_even = [](int i) { return i % 2 == 0; };
auto evens = vet | std::views::filter(is_even);
auto sum = std::accumulate(std::begin(evens), std::end(evens), 0);
Here's a demo.
This is my solution(sorry if it's not right I'm writing it on my phone)
You don't need a vector form this, you just need to check right from the input if the number is divisible to 2
My solution:(a littie bit ugly)
#include <iostream>
using namespace std;
int main()
{
int s {1};
int sum{};
int countNum{};
while (s != 0)
{
cin >> s;
if (s % 2 == 0)
{
sum += s;
countNum++;
}
}
cout << countNum << ' ' << sum;
}
i don't realy know what you want to do in the second part of your code but you can sum the even numbers by this way and i want to told you another thing when you using namespace std you don't need to write std::cin you can only write cin directly
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vet;
int s = 1;
//Take Input
while (s != 0) {
cin >> s;
vet.push_back(s);
}
//count elements
int elements_count = vet.size(); //vet.size() return the total number of elements of vector
//store the sum here
int sum=0;
//loop on the vector and sum only even numbers
for(int i=0;i<elements_count;i++){
if(vet[i] %2 ==0)
sum += vet[i];//check of the element of index i in the vector is even if it true it will add to sum
}
cout << sum;
return 0;
}
int sumEven=0;
int v[100];
int n;//number of elements you want to enter in the array
do{cout<<"Enter n";
cin>>n;}while(n<=0);
//in a normal 1 dimensional array
for(int i=0;i<n;i++)
if(v[i]%2==0)
sumEven+=v[i];
//in a vector
vector<int> v;
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
if(*it%2==0)
sumEven+=v[i];
Similar to answers above, but if you want to keep the vector of even numbers as well, here are two approaches.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
// Hold onto what we know is the right answer.
int known_sum = 2+4+6+8+10;
// Copy only even values into another vector
std::vector<int> even_values;
std::copy_if(vec.begin(), vec.end(),
std::back_inserter(even_values),
[](int val){ return val%2==0; });
// Compute sum from even values vector
int even_value_sum = std::accumulate(even_values.begin(), even_values.end(), 0);
// Compute sum from original vector
int even_value_second = std::accumulate(vec.begin(), vec.end(), 0,
[](int current_sum, int new_value) {
return new_value%2==0 ? current_sum + new_value:current_sum;
}
);
// These should all be the same.
std::cout << "Sum from only even vector: " << even_value_sum << std::endl;
std::cout << "Sum from binary op in std accumulate: " << even_value_second << std::endl;
std::cout << "Known Sum: " << known_sum << std::endl;
}
Range-based for loops
A range-based for loop is arguably always a valid alternative to the STL algos, particularly in cases where the operators for the algos are non-trivial.
In C++14 and C++17
E.g. wrapping a range-based even-only accumulating for loop in an immediately-executed mutable lambda:
#include <iostream>
#include <vector>
int main() {
// C++17: omit <int> and rely on CTAD.
const std::vector<int> v{1, 10, 2, 7, 4, 5, 8, 13, 18, 19};
const auto sum_of_even_values = [sum = 0, &v]() mutable {
for (auto val : v) {
if (val % 2 == 0) { sum += val; }
}
return sum;
}();
std::cout << sum_of_even_values; // 42
}
In C++20
As of C++20, you may use initialization statements in the range-based for loops, as well as the ranges library, allowing you to declare a binary comparator in the initialization statement of the range-based for loop, and subsequently apply it the range-expression of the loop, together with the std::ranges::filter_view adaptor:
#include <iostream>
#include <vector>
#include <ranges>
int main() {
const std::vector v{1, 10, 2, 7, 4, 5, 8, 13, 18, 19};
const auto sum_of_even_values = [sum = 0, &v]() mutable {
for (auto is_even = [](int i) { return i % 2 == 0; };
auto val : v | std::ranges::views::filter(is_even)) {
sum += val;
}
return sum;
}();
std::cout << sum_of_even_values; // 42
}

Switching data from array to vector

I'm trying to convert my array to a vector, yet I'm having trouble printing it.
It says in int main() in my for loop that v is undefined. When I define
vector v; inside int main() the program compiles and runs and yet prints nothing. What am I doing wrong?
#include <iostream>
#include <vector>
using namespace std;
vector<int> a2v(int x[], int n)
{
vector<int> v(n);
for(int i = 0; i < n; i++)
{
v.push_back(x[i]);
}
return(v);
}
int main()
{
vector<int> a2v(int x[], int n);
int array[] = {11,12,13,14,15,16,17,18};
a2v(array, 8);
for(int i = 0; i < v.size(); i++)
{
cout << v[i] <<" ";
}
cout << endl;
return(0);
}
This is your program corrected:
#include <iostream>
#include <vector>
using namespace std;
vector<int> a2v(int x[], int n)
{
vector<int> v(0);
v.reserve(n); //optional
for(int i = 0; i < n; i++)
{
v.push_back(x[i]);
}
return(v);
}
int main()
{
int array[] = {11,12,13,14,15,16,17,18};
auto v = a2v(array, 8);
for(size_t i = 0; i < v.size(); i++)
{
cout << v[i] <<" ";
}
cout << endl;
return(0);
}
There were 2 errors:
In the function a2v, you instantiated a vector of 0 with length n, and then you pushed back other elements;
You were not defining v inside the main, as the return value of a2v
The vector you want to read is the return of the a2v function.
But there is a lot more simpler than that to go from C-array to vector array , I put here the example in found the vector reference web page :
http://www.cplusplus.com/reference/vector/vector/vector/
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
When you define a variable, such as your vector v, you always do it in a certain scope. The body of a function such as a2v, or main, is an example of a possible scope. So if you only do it in the function a2v, that's the only scope where it will be visible.
It says in int main() in my for loop that v is undefined.
Well it will be because there is no v in main()
a2v(array, 8);
The above function call returns a vector so you need to collect the returned vector like
vector<int> v=a2v(array,8)
Also,
vector<int> v(n);//creates a vector of size n
for(int i = 0; i < n; i++)
{
v.push_back(x[i]);//adds n more elements to the vector
}
The returned vector has 2n elements and not n
Finally you could directly create a vector from an array as
vector<int> v(arr,arr+n);//where n is the number of elements in arr

swap array values in c++

I want to shift left array values if my v=4 is in a[n],remove 4 from a[n] and at the end index add 0,how i can do this?
#include <iostream>
using namespace std;
const int n=5;
int main()
{
int a[n]={1,5,4,6,8}, v=4;
int b[n];
cout << "Enter a Value" << endl;
cout<<v<<endl;
for(int i=0; i<n; i++){
cout<<a[i];
}
cout<<endl;
for(int j=0; j<n; j++){
b[j]=a[j];
if(a[j]==v)
b[j]=a[++j];
cout<<b[j];
}
return 0;
}
#include <vector> // needed for vector
#include <algorithm> // needed for find
#include <iostream> // needed for cout, cin
using namespace std;
// Vectors are just like dynamic arrays, you can resize vectors on the fly
vector<int> a { 1,5,4,6,8 }; // Prepare required vector
int v;
cout << "enter value"; // Read from user
cin >> v;
auto itr = find( a.begin(), a.end(), v); // Search entire vector for 'v'
if( itr != a.end() ) // If value entered by user is found in vector
{
a.erase(itr); // Delete the element and shift everything after element
// Toward beginning of vector. This reduces vector size by 1
a.push_back(0); // Add 0 in the end. This increases vector size by 1
}
for( int i : a ) // Iterate through all element of a (i holds element)
cout << i; // Print i
cout << '\n'; // Line end
a few helpful links:
vector , find , iterator , erase , push_back
You could use std::rotate. I suggest that you use std::vector instead of C arrays and take full advantage of the STL algorithms. Nevertheless, below I'm illustrating two versions one with C arrays and one with std::vector:
Version with C array:
#include <iostream>
#include <algorithm>
int main()
{
int const n = 5;
int a[n] = {1,5,4,6,8};
std::cout << "Enter a Value" << std::endl;
int v;
std::cin >> v;
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
auto it = std::find(std::begin(a), std::end(a), v);
if(it != std::end(a)) {
std::rotate(it + 1, it, std::end(a));
a[n - 1] = 0;
}
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
return 0;
}
Version with vector:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> a{1,5,4,6,8};
std::cout << "Enter a Value" << std::endl;
int v;
std::cin >> v;
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
auto it = std::find(std::begin(a), std::end(a), v);
if(it != std::end(a)) {
std::rotate(it + 1, it, std::end(a));
a.back() = 0;
}
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
return 0;
}
Here's an example using std::array
#include <array>
#include <algorithm>
// defines our array.
std::array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
// find the position of the element with the value 4.
auto where = std::find(a.begin(), a.end(), 4);
// if it wasn't found, give up
if (where == a.end())
return 0;
// move every element past "where" down one.
std::move(where + 1, a.end(), where);
// fill the very last element of the array with zero
a[ a.size() - 1] = 0;
// loop over our array, printing it to stdout
for (int i : a)
std::cout << i << " ";
std::cout << "\n";
Why would anyone use these awkward algorithms? Well, there are a few reasons. Firstly, they are container-independant. This will work with arrays and vectors and deques, no problem. Secondly, they can be easily used to work with a whole range of elements at once, not just single items, and can copy between containers and so on. They're also type-independant... you acn have an array of strings, or an vector of ints, or other more complex things, and the algorithms will still work just fine.
They're quite powerful, once you've got over their initial user-unfriendliness.
You can always use either std::array or std::vector or whatever without using the standard library algorithms, of course.
std::array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
size_t where = 0;
int to_remove = 4;
// scan through until we find our value.
while (a[where] != to_remove && where < a.size())
where++;
// if we didn't find it, give up
if (where == a.size())
return 0;
// shuffle down the values
for (size_t i = where; i < a.size() - 1; i++)
a[i] = a[i + 1];
// set the last element to zero
a[ a.size() - 1] = 0;
As a final example, you can use memmove (as suggested by BLUEPIXY) to do the shuffling-down operation in one function call:
#include <cstring>
if (where < a.size() - 1)
memmove(&a[where], &a[where + 1], a.size() - where);

String vector's sort compare and delete

In C++ I have
vector < vector <string> > Kblist;
Inside Kblist, there are many clause, and numbers of clauses=kblist.size(); and every clause in side Kblist is a string-type vector, and every word in sentence is split inside Kblist[i].
What is the fastest way to find the sentence in same words like one in "I love you" and the other in "you love i" and delete these two sentence from Kblist, My code might be work run, but I think it is too slow because of to many circulate. So I wonder is there any better solution which is fast like using sort, clause1==clause2 or other approach.
for (int a=0; a<KBlist.size(); a++){
for (int b=a+1; b<KBlist.size(); b++){
int checksize=0;
if (KBlist[a].size()==KBlist[b].size()) {
for (int c=0; c<KBlist[a].size(); c++){
for (int d=0; d<KBlist[b].size(); d++){
if (KBlist[a][b]==KBlist[c][d]&&KBlist[a][b+1]==KBlist[c][d]) {
checksize=checksize+1;
break;
}
}
}
if (checksize==c.size()) {
inset=1;
break;
}
}
}
}
}while (duplicate==0);
You could iterate over each std::vector and use the algorithms of the standard-library.
There is std::find
// find example
#include <iostream> // std::cout
#include <algorithm> // std::find
#include <vector> // std::vector
int main () {
int myints[] = { 10, 20, 30 ,40 };
int * p;
// pointer to array element:
p = std::find (myints,myints+4,30);
++p;
std::cout << "The element following 30 is " << *p << '\n';
std::vector<int> myvector (myints,myints+4);
std::vector<int>::iterator it;
// iterator to vector element:
it = find (myvector.begin(), myvector.end(), 30);
++it;
std::cout << "The element following 30 is " << *it << '\n';
return 0;
}
there is std::find_if
// find_if example
#include <iostream> // std::cout
#include <algorithm> // std::find_if
#include <vector> // std::vector
bool IsOdd (int i) {
return ((i%2)==1);
}
int main () {
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "The first odd value is " << *it << '\n';
return 0;
}
As you are working with std::string this shouldn't be a large problem.
In your scenario it is probably better to use std::multiset< vector <string> > with comparator that compares std::vector<string> in a way you need it to. This will give you sorted container with duplicated values next to each other and cheap insert/erase.