Display message when the vector is empty - c++

I would like to know how to display a message when a vector is empty. I know what is required but I don't know how to must be structured.
void displaypoints(const vector<int>& vec) {
cout << "[";
for (const auto& i : vec) {
cout << i << ' ';
}
cout << "]" << endl;
};
int main() {
vector <int> myvec {};
vector <int> newvec {1,2,3,4,5};
cout << "myvec";
displaypoints(myvec);
cout << "newvec";
displaypoints(newvec);
if (newvec.at(0) == 1) {
auto iq = find(newvec.begin(), newvec.end(), 1);
if (iq != newvec.end()) {
newvec.erase(iq);
}
if (newvec.begin(), newvec.end(), 2) {
auto ik = find(newvec.begin(), newvec.end(), 2);
if (ik!= newvec.end()) {
myvec.push_back(*ik);
newvec.erase(ik);
}
else if (newvec.begin(), newvec.end(), 3) {
auto ik = find(newvec.begin(), newvec.end(), 3);
if (ik!= newvec.end()) {
myvec.push_back(*ik);
newvec.erase(ik);
}
}
}
}
if (newvec.at(0) == 5) {
auto ik = find(newvec.begin(), newvec.end(), 5);
if (ik!= newvec.end()) {
myvec.push_back(*ik);
newvec.erase(ik);
}
}
displaypoints(newvec);
displaypoints(myvec);
}
The code above looks for the number 1, erases it then moves 2 to the myvec vector. If there is no 2 then it moves 3 because of the position 0 I have added. There is also another if statement that moves 5 if it is placed at position 0. What I want is another if statement to print a message if there is nothing in the newvec vector.

void displaypoints(vector<int> & vec){
if(vec.empty()){
cout<<"Vector Empty \n";
}
else {
//do your operations
}
}
whatever Ide you are using try first clean build and then build all and run the code it will work.

#include <algorithm>
#include <iostream>
#include <vector>
void
display_points(const std::vector<int>& v)
{
if (v.empty()) {
std::cout << "Empty vector.\n";
} else {
std::cout << "[ ";
for (const auto& i : v) {
std::cout << i << ' ';
}
std::cout << "]\n";
}
}
int
main()
{
std::vector<int> myvec;
std::vector<int> newvec{ 1, 2, 3, 4, 5 };
std::cout << "myvec: ";
display_points(myvec);
std::cout << "newvec:";
display_points(newvec);
int i = 1;
while (newvec.size() > 0) {
auto it = std::find(newvec.begin(), newvec.end(), i);
if (it != newvec.end()) {
myvec.push_back(*it);
newvec.erase(it);
}
++i;
}
std::cout << "myvec: ";
display_points(myvec);
std::cout << "newvec:";
display_points(newvec);
}

Related

Understanding priority_queue by problem : Find K Closest Elements Solution

I was solving one problem on leetcode problem - Find K Closest Elements.
Here is my IDE code : ide.geeksforgeeks
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
std::vector<int> findClosestElements(std::vector<int>& arr, int k, int x)
{
std::vector<int> res;
// min heap
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>,
std::greater<std::pair<int, int>>> pq;
std::cout << "Debug queue : \n";
for (auto it : arr)
{
int closest = abs(it - x);
pq.push(std::make_pair(closest, it));
//std::cout << closest << " : " << it << "\n";
if (pq.size() > k)
{
pq.pop();
}
}
std::cout << "\nIterating queue : \n";
while(!pq.empty())
{
res.push_back(pq.top().second);
std::cout << pq.top().first << " : " << pq.top().second << "\n";
pq.pop();
}
std::sort(res.begin(), res.end());
return res;
}
int main()
{
std::vector<int> arr = {1,2,3,4,5};
auto res = findClosestElements(arr, 4, 3);
return 0;
}
While I was iterating the queue, I can not see the minimum number : 0 : 3 which should be the top element of priority_queue. Can anyone please suggest?
Max heaps solves the problem.
vector<int> findClosestElements(vector<int>& arr, int k, int x)
{
std::vector<int> res;
std::priority_queue<std::pair<int, int>> pq;
for (auto it : arr)
{
int closest = abs(it - x);
//std::cout << closest << " : " << it << "\n";
pq.push(std::make_pair(closest, it));
if (pq.size() > k)
{
pq.pop();
}
}
//std::cout << "\nDebug queue : \n";
while(!pq.empty())
{
res.push_back(pq.top().second);
//std::cout << pq.top().first << " : " << pq.top().second << "\n";
pq.pop();
}
std::sort(res.begin(), res.end());
return res;
}

Sorting function returns wrong object type on C++17

For some reason when I try to compile the following code with the -std=c++17 flag I get the following error.
The code:
#include <functional>
#include <iostream>
#include <list>
std::list<int> partition(std::list<int>::const_iterator &&begin,
std::list<int>::const_iterator &&end,
std::function<bool(int)> predicate) {
std::list<int> result;
while (begin != end) {
if (predicate(*begin)) {
result.push_front(*begin);
} else {
result.push_back(*begin);
}
begin++;
}
return result;
}
int main() {
std::list<int> numbers{15, 20, 25, -10, -75, 100, -255, 430, 200};
std::cout << "Original list:" << std::endl;
for (int &e : numbers) {
std::cout << e << " ";
}
std::cout << std::endl << std::endl;
std::cout << "[](int num) { return !(num % 2); }" << std::endl;
std::list<int> result = partition(numbers.cbegin(), numbers.cend(), [](int num) { return !(num % 2); });
for (int &e : result) {
std::cout << e << " ";
}
std::cout << std::endl;
return 0;
}
The error:
main.cpp: In function ‘int main()’:
main.cpp:31:36: error: conversion from ‘std::_List_const_iterator<int>’ to non-scalar type ‘std::__cxx11::list<int>’ requested
31 | std::list<int> result = partition(numbers.cbegin(), numbers.cend(),
| ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
32 | [](int num) { return !(num % 2); });
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For some reason when I create a std::function<bool(int)> and store the lambda inside it, then pass the function pointer I don't get this error
Code that works:
#include <functional>
#include <iostream>
#include <list>
std::list<int> partition(std::list<int>::const_iterator &&begin,
std::list<int>::const_iterator &&end,
std::function<bool(int)> predicate) {
std::list<int> result;
while (begin != end) {
if (predicate(*begin)) {
result.push_front(*begin);
} else {
result.push_back(*begin);
}
begin++;
}
return result;
}
int main() {
std::list<int> numbers{15, 20, 25, -10, -75, 100, -255, 430, 200};
std::cout << "Original list:" << std::endl;
for (int &e : numbers) {
std::cout << e << " ";
}
std::cout << std::endl << std::endl;
std::cout << "[](int num) { return !(num % 2); }" << std::endl;
std::function<bool(int)> func = [](int num) { return !(num % 2); };
std::list<int> result = partition(numbers.cbegin(), numbers.cend(), func);
for (int &e : result) {
std::cout << e << " ";
}
std::cout << std::endl;
return 0;
}
Does anyone know the reason for this behavior? When I compile without the std flag, or when I compile on Windows I don't get that error. GCC version 10.2., on Arch Linux.
The partition function returns an iterator!
Try this:
std::list<int>::iterator result = partition(numbers.cbegin(), numbers.cend(), [](int num) { return !(num % 2); });

What should i do to optimize this C++ code? I don't have any idea which statement is taking more execution time

I was to solve one question on hackerrank related to lower bound in C++. My code was able to pass all the test cases which had no time limit but failed in all time bound test cases. You can find the hackerrank question from this link:
https://www.hackerrank.com/challenges/cpp-lower-bound/problem?utm_campaign=social-buttons&utm_medium=linkedin&utm_source=challenge
Below is my code. Please tell me how I can optimize it.
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::vector<int> v;
int elementCount = 0, queryCount = 0, tempElement = 0;
std::cin >> elementCount;
for(int i=0; i<elementCount; ++i)
{
std::cin >> tempElement;
v.push_back(tempElement);
}
std::vector<int>::iterator elementPosition;
const std::vector<int>::iterator midElement = v.begin() + v.size()/2;
std::cin >> queryCount;
for(int q=0; q<queryCount; ++q)
{
std::cin >> tempElement;
if(tempElement <= *midElement)
{
elementPosition = find(v.begin(), midElement+1, tempElement);
if(elementPosition == (midElement+1))
{
elementPosition = lower_bound(v.begin(), midElement, tempElement);
std::cout << "No " << (elementPosition-v.begin())+1 << std::endl;
}
else
{
std::cout << "Yes " << (elementPosition-v.begin())+1 << std::endl;
}
}
else
{
elementPosition = find(midElement+1, v.end(), tempElement);
if(elementPosition != v.end())
{
std::cout << "Yes " << (elementPosition-v.begin())+1 << std::endl;
}
else
{
elementPosition = lower_bound(midElement+1, v.end(), tempElement);
std::cout << "No " << (elementPosition-v.begin())+1 << std::endl;
}
}
}
return 0;
}
You have over complicated the solution with unnecessary find() + lower_bound.
Just use lower_bound() to find the element
If found, print yes
If not, print no
auto elementPosition = lower_bound(v.begin(), v.end(), tempElement);
size_t pos = std::distance(v.begin(), elementPosition);
if (v[pos] == tempElement) {
//print yes
} else {
// print no
}

How to iterate through a map of vectors while deleting?

I have a map of vectors in C++. For each vector, I'd like to delete entries that meet a certain condition. If a vector ends up empty, I'd like to delete it from the map. I know deletion can mess up iterators, and doubly iterating makes this even more confusing for me. What's the best way to accomplish this?
The standard mutating container loop:
for (auto it = m.begin(); it != m.end(); )
{
// work
if (/* need to delete */) // e.g "if (it->second.empty())"
{
it = m.erase(it);
}
else
{
++it;
}
}
Here is a demonstrative program that shows how it can be done
#include <iostream>
#include <map>
#include <vector>
int main()
{
std::map<int, std::vector<int>> m =
{
{ 1, { 1, 2 } },
{ 2, { 2 } },
{ 3, { 3, 4 } },
{ 4, { 4 } }
};
for ( const auto &p : m )
{
std::cout << p.first << ": ";
for ( int x : p.second ) std::cout << x << ' ';
std::cout << std::endl;
}
for ( auto it = m.begin(); it != m.end(); )
{
it->second.erase( it->second.begin() );
if ( it->second.empty() ) it = m.erase( it );
else ++it;
}
std::cout << std::endl;
for ( const auto &p : m )
{
std::cout << p.first << ": ";
for ( int x : p.second ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
The program output is
1: 1 2
2: 2
3: 3 4
4: 4
1: 2
3: 4

how do I get sequence of 'false' in an array

I am the beginner of C++, and any help will be very appreciated.
here is the code i can run successfully:
#include <Eigen/Dense>
#include <iostream>
using namespace Eigen;
main(){
bool findIn=false;
RowVectorXd A(10);
A<<false,true,false,true,true,false,false,false,true,true;
std::cout << A << std::endl;
for (int i=0;i<A.size();i++){
if(A(i)==findIn){
std::cout << i << std::endl;
}
}
system("pause");
}
the result is {0,2,5,6,7}, and I want to design a function, the code is as follows:
int seq(bool findIn, VectorXd &resdX){
VectorXd A;
for(int i=0;i<resdX.size();i++){
if(resdX(i)==findIn){
A =A+i;
}
}
return(A);
}
I want this function to return result like that {0,2,5,6,7}.But I don`t know how to set up a array to save the result or is there a function just like 'which' in R software to produce sequence above.
Sounds like you want a vector of integers:
#include <vector>
std::vector<int> seq(bool findIn, VectorXd &resdX)
{
std::vector<int> v;
for(int i=0;i<resdX.size();i++) {
if (resdX(i) == findIn) {
v.push_back(i);
}
}
return v;
}
You can then print its contents by iterating through it:
std::vector<int> result = seq(false, A);
for (int i : result) std::cout << i << '\n';
I did not understand what are you looking for.
If you want just to print a sequence of integers indexing findIn values you might code:
void seq(bool findIn, VectorXd &resdX) { // not int
std::cout << "{ ";
for(int i=0;i<resdX.size();i++) // go inside the array
if(resdX(i)==findIn) // if you find that resdX(i) value equals findIn value
std::cout << i << " "; // print i index
std::cout << "}" << std::endl; // at the end prints a new line
}
EDIT1:
Try to adapt the following snippet:
#include <list>
...
std::list<int> seq(bool findIn, VectorXd& resdX) {
std::list<int> l;
for(int i=0; i<resdX.size(); i++) {
if (resdX(i) == findIn) {
l.push_back(i);
}
}
return l;
}
void print_seq(std::list<int> list_) {
std::cout << "{ ";
std::list<int>::iterator it = list_.begin();
for (; it != list_.end(); ++it) {
std::cout << i << " ";
}
std::cout << " }\n";
}