Vector comparison - c++

Vector function emplace()
My emplace function does not work. Any help would be appreciated
vector <int> vec1;
vector <int> vec2(4,0);
vector <int>::iterator iter1;
vector <int>::iterator iter2;
srand(time(NULL));
for(i=0; i<5; i++){
n =rand()%10+1;
vec1.push_back(n);
}
for(iter1=vec1.begin();iter1<vec1.end();iter1++){
for(iter2=vec2.begin();iter2<vec2.end();iter2++){
if(*iter1<=*iter2){
//vec2.emplace(iter1,*iter1);
//print();
}
}
}

for(iter2=vec2.begin();iter2<vec2.end();iter2++){
Because vec2 starts populated with four values of 0, you will never find an element where *iter1 <= *iter2 unless *iter1 == 0.
Instead of zero-initializing it to avoid allocations, you want to reserve space.
vec2.reserve(vec1.size());
and then instead of a for loop you can use std::lower_bound to find the insert location:
#include <iostream>
#include <vector>
#include <algorithm>
void print_vec(const char* label, const std::vector<int>& vec) {
std::cout << label << ": ";
for (int v : vec) {
std::cout << v << ", ";
}
std::cout << "\n";
}
int main() {
std::vector <int> vec1 { 4, 1, 2, 2, 5 };
std::vector <int> vec2;
print_vec("v1", vec1);
vec2.reserve(vec1.size());
for (int v : vec1) {
auto it = std::lower_bound(vec2.begin(), vec2.end(), v);
if (it == vec2.end() || *it != v)
vec2.emplace(it, v);
print_vec("v2", vec2);
}
print_vec("Fin", vec2);
return 0;
}
Live demo: http://ideone.com/o5td9K

What you are trying to do is like insertion sort.
https://en.wikipedia.org/wiki/Insertion_sort
has the pseudo-code. At each step you will check every element in vector 2 and place the new element where it belongs (while loop).

Related

Deleting both an element and its duplicates in a Vector in C++

I've searched the Internet and known how to delete an element (with std::erase) and finding duplicates of an element to then delete it (vec.erase(std::unique(vec.begin(), vec.end()),vec.end());). But all methods only delete either an element or its duplicates.
I want to delete both.
For example, using this vector:
std::vector<int> vec = {2,3,1,5,2,2,5,1};
I want output to be:
{3}
My initial idea was:
void removeDuplicatesandElement(std::vector<int> &vec)
{
std::sort(vec.begin(), vec.end());
int passedNumber = 0; //To tell amount of number not deleted (since not duplicated)
for (int i = 0; i != vec.size(); i = passedNumber) //This is not best practice, but I tried
{
if (vec[i] == vec[i+1])
{
int ctr = 1;
for(int j = i+1; j != vec.size(); j++)
{
if (vec[j] == vec[i]) ctr++;
else break;
}
vec.erase(vec.begin()+i, vec.begin()+i+ctr);
}
else passedNumber++;
}
}
And it worked. But this code is redundant and runs at O(n^2), so I'm trying to find other ways to solve the problem (maybe an STL function that I've never heard of, or just improve the code).
Something like this, perhaps:
void removeDuplicatesandElement(std::vector<int> &vec) {
if (vec.size() <= 1) return;
std::sort(vec.begin(), vec.end());
int cur_val = vec.front() - 1;
auto pred = [&](const int& val) {
if (val == cur_val) return true;
cur_val = val;
// Look ahead to the next element to see if it's a duplicate.
return &val != &vec.back() && (&val)[1] == val;
};
vec.erase(std::remove_if(vec.begin(), vec.end(), pred), vec.end());
}
Demo
This relies heavily on the fact that std::vector is guaranteed to have contiguous storage. It won't work with any other container.
You can do it using STL maps as follows:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
void retainUniqueElements(vector<int> &A){
unordered_map<int, int> Cnt;
for(auto element:A) Cnt[element]++;
A.clear(); //removes all the elements of A
for(auto i:Cnt){
if(i.second == 1){ // that if the element occurs once
A.push_back(i.first); //then add it in our vector
}
}
}
int main() {
vector<int> vec = {2,3,1,5,2,2,5,1};
retainUniqueElements(vec);
for(auto i:vec){
cout << i << " ";
}
cout << "\n";
return 0;
}
Output:
3
Time Complexity of the above approach: O(n)
Space Complexity of the above approach: O(n)
From what you have searched, we can look in the vector for duplicated values, then use the Erase–remove idiom to clean up the vector.
#include <vector>
#include <algorithm>
#include <iostream>
void removeDuplicatesandElement(std::vector<int> &vec)
{
std::sort(vec.begin(), vec.end());
if (vec.size() < 2)
return;
for (int i = 0; i < vec.size() - 1;)
{
// This is for the case we emptied our vector
if (vec.size() < 2)
return;
// This heavily relies on the fact that this vector is sorted
if (vec[i] == vec[i + 1])
vec.erase(std::remove(vec.begin(), vec.end(), (int)vec[i]), vec.end());
else
i += 1;
}
// Since all duplicates are removed, the remaining elements in the vector are unique, thus the size of the vector
// But we are not returning anything or any reference, so I'm just gonna leave this here
// return vec.size()
}
int main()
{
std::vector<int> vec = {2, 3, 1, 5, 2, 2, 5, 1};
removeDuplicatesandElement(vec);
for (auto i : vec)
{
std::cout << i << " ";
}
std::cout << "\n";
return 0;
}
Output: 3
Time complexity: O(n)

Finding multiple max elements in a vector C++

So.. I am trying to find the maximum value of a vector and its position in the vector. I am using a for loop, and it's working fine. My problem is, that if the maximum value appears more than once, I want to know all the positions in which it appears in the vector.. So, how could I manage this?
So far, this is the code I am using: (the vector called v has elements that I read from a file but I will not add that part of the code)
std::vector<double>v;
double maxvalue;
int position=0;
maxvalue = v[0];
for (unsigned int i=0; i<v.size(); i++){
if (v[i]> maxvalue){
maxvalue=v[i];
position= i;
}
}
You could modify your approach to keep a vector of indices where the maximum occurred:
#include <cfloat>
#include <iostream>
#include <utility>
#include <vector>
std::pair<double, std::vector<std::size_t>> FindMaxElements(std::vector<double> const& v)
{
std::vector<std::size_t> indices;
double current_max = -DBL_MAX;
for (std::size_t i = 0; i < v.size(); ++i)
{
if (v[i] > current_max)
{
current_max = v[i];
indices.clear();
}
if (v[i] == current_max)
{
indices.push_back(i);
}
}
return std::make_pair(current_max, indices);
}
int main()
{
auto result = FindMaxElements({1, 4, 7, 2, 7, 3});
std::cout << "max: " << result.first << '\n';
std::cout << "indices: ";
for (auto i : result.second)
std::cout << i << ' ';
}
Output
max: 7
indices: 2 4
Here is a two-pass version using the standard library (whereas it might be cleaner without it):
#include <vector>
#include <algorithm>
int main()
{
std::vector<double> v {/* fill it*/ };
std::vector<int> pos;
auto it = std::max_element(std::begin(v), std::end(v));
while (it != std::end(v))
{
pos.push_back(std::distance(std::begin(v), it));
it = std::find(std::next(it), std::end(v), *it);
}
//...
}
The function template below, find_maximums(), returns an std::vector<size_t> that contains the positions where the maximums are in the input vector. Note that it returns an empty vector of indexes if the input vector is empty.
template<typename T>
auto find_maximums(const std::vector<T>& v) {
std::vector<size_t> indexes;
for (auto it_max = std::max_element(v.begin(), v.end()); it_max != v.end();
it_max = std::find(it_max+1, v.end(), *it_max))
{
auto index = std::distance(v.begin(), it_max);
indexes.push_back(index);
}
return indexes;
}
As an example of use:
auto main() -> int {
std::vector<int> v = {11, 7, 3, 11, 0, 7, 1, 11, 11};
auto max_indexes = find_maximums(v);
if (max_indexes.empty())
return 1;
std::cout << "max: " << v[max_indexes.front()] << std::endl;
std::cout << "max at positions: ";
for (auto idx: max_indexes)
std::cout << idx << ' ';
std::cout << '\n';
}
It outputs:
max: 11
max at positions: 0 3 7 8
Passing a couple of iterators and a comparator
template <class It,
class Comp = std::less<typename std::iterator_traits<It>::value_type>>
auto max_elements_indices(It first, It last, Comp cmp = Comp{})
{
// This function returns a vector of indices, so to get the maximum, the caller
// should first check if the returned vector is empty and then use one of
// those indices to retrieve the value.
std::vector<std::size_t> indices;
if (first == last)
return indices;
// Using the first element instead of a sentinel value is easier to generalize
indices.push_back(0);
auto value = *first;
for (auto i = std::next(first); i != last; ++i)
{
// The most common case should be an element below the maximum
if ( cmp(*i, value) )
continue;
else
{
if ( cmp(value, *i) )
{
value = *i;
indices.clear();
}
indices.push_back(std::distance(first, i));
}
}
return indices;
}
It is testable here.

Suppose we have two std::vectors v1 and v2 and we dont want to combine these in a struct. How to transform v2 the same way v1 was transformed by sort?

This is a followup of this question. The only difference is the constrain that the two vectors cannot be combined in a struct.
Suppose we have a vector
std::vector<double> v1 = {9.0,5.0,3.0,2.0,1.0};
Now we sort the vector v1. Let v2 be given by
std::vector<std::string> v2 = {"you?","are","how","there","hello"};
How to transform v2 the same way v1 was transformed by sort?
Based on this answer, you can use an array of indices to "sort" the vector of doubles, and just use the resulting index array to index the vector of strings.
#include <algorithm>
#include <iostream>
#include <string>
#include <numeric>
int main()
{
std::vector<double> v1 = {5.0,9.0,3.0,2.0,1.0};
std::vector<std::string> v2 = {"are", "you?","how","there","hello"};
// Create an array of indices, starting from 0
std::vector<int> index(v1.size());
std::iota(index.begin(), index.end(), 0);
// "Sort" the index array according to the value in the vector of doubles
std::sort(index.begin(), index.end(),
[&](int n1, int n2){ return v1[n1] < v1[n2]; });
// Output results
for (auto i : index )
std::cout << v2[i] << " " << v1[i] << ", index is " << i << "\n";
}
Output:
hello 1, index is 4
there 2, index is 3
how 3, index is 2
are 5, index is 0
you? 9, index is 1
Note:
I changed the original data to illustrate how the index array works.
The abstraction you are missing is the ability to view the vectors as one item. That's the role that a vector of indices is a proxy for in another answer.
I think it is worth mentioning that there are libraries that provide such a concept (often under the name "zip"). For example, with range-v3:
std::vector<double> v1 = {5, 9, 3, 2, 1};
std::vector<std::string> v2 = {"are", "you?", "how", "there", "hello"};
// Sort the vectors
ranges::actions::sort(ranges::views::zip(v1, v2));
// Output results
for (std::size_t i = 0; i < v1.size(); ++i)
std::cout << v2[i] << " " << v1[i] << ", index is " << i << "\n";
A possible solution uses a helper std::vector<int>:
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
template<typename T>
void MySort(std::vector<T> t, std::vector<int>& helper)
{
struct StructHelper
{
T t1;
int num;
StructHelper(T t, int i): t1{t}, num{i} {};
bool operator<(const StructHelper& other) const
{ return t1 < other.t1; }
};
std::vector<StructHelper> shVector;
for(int i=0; i<t.size(); ++i)
{
shVector.emplace_back(t[i], i);
}
std::sort(shVector.begin(), shVector.end());
helper = std::vector<int>(t.size());
for(int i=0; i<t.size(); ++i)
{
helper[i] = shVector[i].num;
}
}
template<typename T>
void MySortUsingHelper(std::vector<T>& t1, const std::vector<int>& helper)
{
if(t1.size() != helper.size()) throw std::out_of_range("not same size");
std::vector<T> t2(t1.size());
for(int i=0; i<helper.size(); ++i)
{
t2[i] = t1[helper[i]];
}
t1 = t2;
}
int main() {
std::vector<double> v1 = {9.0,5.0,3.0,2.0,1.0};
std::vector<int> helper;
MySort(v1, helper);
std::vector<std::string> v2 = {"you?","are","how","there","hello"};
MySortUsingHelper(v2, helper);
for(auto elem : v2)
{
std::cout << elem << " ";
}
return 0;
}
You can run the above code online to see the following output:
hello there how are you?

How to insert multiple elements in the vector at different positions using iterator?

I want to write a function that changes the vector [2, 1, 4, 0, 5] to
[2, 2, 1, 4, 4, 4, 4, 5, 5, 5, 5, 5]
I could do it by popping the vector into an array and then pushing the elements back to the vector.
How can I use insert to do it? Can I modify the following program? What is the most efficient way?
void timesDuplicates(vector<int>& a)
{
int s = a.size(), count = 0;
for(int i = 0; count < s ; i+=a[i], count++) {
if(a[i] == 0) continue;
a.insert(a.begin()+i, a[i], a[i]);
}
}
How can I use insert to do it? Can I modify the following program?
Regarding efficiency, your vector might undergo several reallocations on each time when insertion happens, as in provided code no memory has been std::vector::reserve ed, even it could have been done by summing up the elements. Like #IgorTandetnik pointed out, transforming the passed vector, wouldn't be possible as well.
The easiest way you could do is, create a new vector in which simply std::vector::insert elements as per the number of elements exist in the passed vector.
Following is an example code. (See Live)
#include <iostream>
#include <vector>
#include <numeric> // std::accumulate
std::vector<int> timesDuplicates(const std::vector<int>& vec)
{
std::vector<int> result;
// reserve the amount of memory for unwanted reallocations
result.reserve(std::accumulate(std::cbegin(vec), std::cend(vec), 0));
// you do not need to check element == 0 here
// as std::vector::insert(end, 0, 0) will insert nothing
for (const int element : vec) result.insert(result.end(), element, element);
// return the result
return result;
}
int main()
{
const auto result{ timesDuplicates({ 2, 1, 4, 0, 5 }) };
for (const int ele : result) std::cout << ele << " ";
return 0;
}
Or if you do not believe in NRVO or copy elision to happen, pass the vector result as a parameter(ref) to the function, after reserving the memory that it needs.
#include <iostream>
#include <vector>
#include <numeric> // std::accumulate
void timesDuplicates(
const std::vector<int>& vec,
std::vector<int>& result)
{
for (const int element : vec)
result.insert(result.end(), element, element);
}
int main()
{
const std::vector<int> vec{ 2, 1, 4, 0, 5 };
std::vector<int> result;
result.reserve(std::accumulate(std::cbegin(vec), std::cend(vec), 0));
timesDuplicates(vec, result);
for (const int ele : result) std::cout << ele << " ";
return 0;
}
Try this snippet with recursion. Since you are popping and pushing into a new temporary vector, push_back will suffice ( insert will require you to locate new insert positions)
void timesDuplicates(vector<int>& vec, int idx = 0)
{
static vector<int> result;
int v = vec[idx]; // get value
for (int i = 0; i < v; i++) // multiply value
{
result.push_back(v); // push value to temp vector (result)
}
if (idx == vec.size() - 1) { // border condition
vec.swap(result); // swap result
return;
}
timesDuplicates(vec, ++idx); // increment index
}
void main()
{
vector<int> vec = { 2, 1, 4, 0, 5 };
timesDuplicates(vec);
for (auto e : vec)
cout << e << " ";
cout << "\n";
}

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);