Given a std::vector, for example of ints
std::vector vec{10, 20, 30}
how to select all items except of with given index, for example int i=1 resulting
std::vector {10, 30}?
If you just want to "select" values from the original vector, I would create another vector with all the new values.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vect{ 10, 20, 30 };
vector<int> selected;
int i = 1;
for (int j = 0; j < vect.size(); j++) {
if (j != i) {
selected.push_back(vect[j]);
}
}
// Added so you can check the new values
for (int z = 0; z < selected.size(); z++) {
cout << selected[z] << " ";
}
return 0;
}
However, if you want to erase values from your original vector I would recommend using the vector.erase method (research the documentation).
Here is a function for it where you can pass the vector and index and it will return you the new vector without that index element.
#include <iostream>
#include <vector>
using namespace std;
// returns a new vector without the v[index]
vector<int> getElementsExceptIndex(vector<int> v, int index){
vector<int> newVector;
for(auto &x:v ){
if(( &x - &v[0]) != index)
newVector.push_back(x);
}
return newVector;
}
int main() {
vector<int> originalVector{ 10, 20, 30 ,33,53};
int index=1;
auto RemovedIndexVector = getElementsExceptIndex(originalVector,index);
for(auto item:RemovedIndexVector)
cout<<item<<" ";
return 0;
}
// Output - 10 30 33 53
Hope this helps
Related
I have a function that returns a vector and I want all of that vector inserted into another vector at a specific point directly when calling that function.
What I would like to do is something like this:
#include <vector>
#include <iostream>
using namespace std;
typedef vector<double> Double1D;
Double1D myFunction(Double1D vector, int vector_size){
Double1D result;
result.resize (vector_size, 0);
result = vector; //here is where I would do calculations
return result;
}
int main()
{
int vector_size1 = 3;
int vector_size2 = 6;
Double1D vector_results;
vector_results.resize (9, 3);
vector_results[0-2] = myFunction(randomvector, vector_size1);
vector_results[3-8] = myFunction(randomvector2, vector_size2);
At the moment I am doing this which needs a for loop and needs extra temporary variables (minimal reproducible example):
#include <vector>
#include <iostream>
using namespace std;
typedef vector<double> Double1D;
Double1D myFunction(Double1D vector, int vector_size){
Double1D result;
result.resize (vector_size, 0);
result = vector; //here is where I would do calculations
return result;
}
int main()
{
int vector_size1 = 3;
int vector_size2 = 6;
Double1D vector_results;
vector_results.resize (9, 3);
Double1D vector1 ;
vector1.resize (vector_size1, 0);
Double1D vector2 ;
vector2.resize (vector_size2, 0);
Double1D temp_vector1 = myFunction(vector1, vector_size1);
Double1D temp_vector2 = myFunction(vector2, vector_size2);
for (int i = 0; i < (vector_size1 + vector_size2); i++){
if (i < vector_size1) vector_results[i] = temp_vector1[i];
if (i < vector_size2) vector_results[i+vector_size1] = temp_vector2[i];
cout<<vector_results[i]<<endl;
}
return 0;
}
The idiomatic method for writing a range of results is to take OutputIterators as function parameters.
#include <vector>
using Double1D = std::vector<double>;
void myFunction(Double1D::iterator dFirst, Double1D::iterator dLast) {
int n = /* number between 0 and dLast - dFirst */
dFirst[n] = /* calculations */
// or
for (; dFirst != dLast; ++dFirst) {
*dFirst = /* calculation */
}
}
int main() {
Double1D array_results;
array_results.resize(9, 0);
myFunction(randomvector, vector_size1);
myFunction(randomvector1, vector_size2);
}
If you insist on assigning a Double1D to something:
class AssignableSlice {
Double1D::iterator first;
Double1D::iterator last;
public:
AssignableSlice(Double1D & values, size_t first, size_t last)
: first(values.begin() + first), last(values.begin() + last) {}
AssignableSlice& operator=(Double1D & other) {
if (other.size() != std::distance(first, last)) throw std::out_of_range("wrong size in assignment");
std::copy(other.begin(), other.end(), first, last);
return *this;
}
};
int main() {
Double1D vector1;
vector1.resize (vector_size1, 0);
Double1D vector2;
vector2.resize (vector_size2, 0);
Double1D array_results;
array_results.resize(9, 0);
AssignableSlice(array_results, 0, vector_size1) = myFunction(vector1, vector_size1);
AssignableSlice(array_results, vector_size1, vector_size1 + vector_size2) = myFunction(vector2, vector_size2);
}
G'day, Alex from the past. This is you from the future. Here is how you solved it.
The function you want to use is a vector function called: insert() or a more efficient way that works for you is using copy() with back_inserter().
copy with back_inserter can only insert the vector to the back, whereas insert allows to insert anywhere. Both increase the size of the vector automatically.
Disclaimer: This may not be the best solution I am not an expert.
#include <vector>
#include <iostream>
using namespace std;
//vector<double> is variable that is a vector of doubles
typedef vector<double> Double1D; //this basically just gives vector<double> the name Double1D to make it easier to write
Double1D myFunction(Double1D vector, int vector_size){
Double1D result;
result.resize (vector_size, 0);
result = vector; //here is where I would do calculations
return result;
}
int main()
{
int vector_size1 = 3;
int vector_size2 = 6;
Double1D vector_results(vector_size1+vector_size2, 0);//fill vector with vector_size1+vector_size2 many 0s
Double1D vector1(vector_size1,1) ;//fill vector with vector_size1 many 1s
Double1D vector2(vector_size2, 2) ; //fill vector with vector_size2 many 1s
for (int i = 0; i < vector_results.size(); i++){ //see that it is full of 0s
cout<<vector_results[i]<<" ";
}
cout<<endl;
//this is specifically what you asked for
vector_results = myFunction(vector1, vector_size1); //vector_results is now just a copy of the vector of the output of the function
for (int i = 0; i < vector_results.size(); i++){
cout<<vector_results[i]<<" ";
}
cout<<endl;
//yourvectorname.insert(where to insert (an iterator), what to insert beginning, what to insert end)
//vector_results.insert(vector_results.begin()+3, myFunction(vector2, vector_size2).begin(), myFunction(vector2, vector_size2).end()); //this doesnt work as I think the function gets called twice?
Double1D temp_vec = myFunction(vector2, vector_size2);
vector_results.insert(vector_results.begin()+vector_size1, temp_vec.begin(), temp_vec.end());
for (int i = 0; i < vector_results.size(); i++){
cout<<vector_results[i]<<" ";
}
cout<<endl;
//here is a version using back_inserter which I have read is more efficient
//whatever you want at the start you just overwrite the destined vector with it
vector_results = myFunction(vector1, vector_size1); //vector_results is now just a copy of the vector of the output of the function
//create a tempvector to be able to use it
Double1D temp_vec2 = myFunction(vector2, vector_size2);
//now the important part: copy(start of what you wanna copy,end of what you wanna copy, where you want to insert it)
copy(temp_vec2.begin(), temp_vec2.end(), back_inserter(vector_results)); //back_inserter inserts it at the back (and from what I read more efficient than an insert in the middle)
for (int i = 0; i < vector_results.size(); i++){
cout<<vector_results[i]<<" ";
}
cout<<endl;
return 0;
}
I'm trying to fill 2D vector in C++ with characters, but when I run this code it ends with one line characters (*..).
How can I fill 2D vector like this:
*.*
.**
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<char> > vec2D;
std::vector<char> rowV;
unsigned int row=2;
unsigned int col=3;
char c;
unsigned int temp=0;
while(temp!=col)
{
while(rowV.size()!=row)
{
std::cin>>c;
rowV.push_back(c);
}
vec2D.push_back(rowV);
++temp;
}
return 0;
}
You should clear rowV after each insertion, otherwise it will be full and no other characters will be added. Also, row should be swapped by col and vice-versa, otherwise you will get a 3x2 (and not 2x3) 2D vector.
while(temp!=row)
{
while(rowV.size()!=col)
{
std::cin>>c;
rowV.push_back(c);
}
vec2D.push_back(rowV);
rowV.clear(); // clear after inserting
++temp;
}
It helps to know what [pushing back a 2DVector with an empty 1D vector] looks like.
See the example below.
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
//-v-----A FUNCTION TO PRINT 2D VECTORS
template<typename T> //We don't know what type the elements are yet, so we use a template
void printVec2D(vector<vector<T>> a) // a is the name of our input 2Dvector of type (T)
{
for (int i = 0; i < a.size(); i++) {// a.size() will equal the number of rows (i suppose rows/columns can depend on how you look at it)
for (int j = 0; j < a[i].size(); j++) {// a[i].size() is the size of the i'th row (which equals the number of columns, foro a square array)
std::cout << a[i][j] << "\t";
}
std::cout << "\n";
}
return;
}
//-^--------
int main()
{
int X = 3; int Y = 3;
int VectorAsArray[3][3] = {{1,2,3},
{14,15,16},
{107,108,109}};
vector<vector<int>> T;
for (int i = 0; i < X; i++)
{
T.push_back({});// We insert a blank row until there are X rows
for (int j = 0; j < Y; j++)
{
T[i].push_back(VectorAsArray[i][j]); //Within the j'th row, we insert the element corresponding to the i'th column
}
}
printVec2D(T);
//system("pause"); //<- I know that this command works on Windows, but unsure otherwise( it is just a way to pause the program)
return 0;
}
I'm trying to delete all elements of an array that match a particular case.
for example..
if(ar[i]==0)
delete all elements which are 0 in the array
print out the number of elements of the remaining array after deletion
what i tried:
if (ar[i]==0)
{
x++;
}
b=N-x;
cout<<b<<endl;
this works only if i want to delete a single element every time and i can't figure out how to delete in my required case.
Im assuming that i need to traverse the array and select All instances of the element found and delete All instances of occurrences.
Instead of incrementing the 'x' variable only once for one occurence, is it possible to increment it a certain number of times for a certain number of occurrences?
edit(someone requested that i paste all of my code):
int N;
cin>>N;
int ar[N];
int i=0;
while (i<N) {
cin>>ar[i];
i++;
}//array was created and we looped through the array, inputting each element.
int a=0;
int b=N;
cout<<b; //this is for the first case (no element is deleted)
int x=0;
i=0; //now we need to subtract every other element from the array from this selected element.
while (i<N) {
if (a>ar[i]) { //we selected the smallest element.
a=ar[i];
}
i=0;
while (i<N) {
ar[i]=ar[i]-a;
i++;
//this is applied to every single element.
}
if (ar[i]==0) //in this particular case, we need to delete the ith element. fix this step.
{
x++;
}
b=N-x;
cout<<b<<endl;
i++;
}
return 0; }
the entire question is found here:
Cut-the-sticks
You could use the std::remove function.
I was going to write out an example to go with the link, but the example form the link is pretty much verbatim what I was going to post, so here's the example from the link:
// remove algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::remove
int main () {
int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20
// bounds of range:
int* pbegin = myints; // ^
int* pend = myints+sizeof(myints)/sizeof(int); // ^ ^
pend = std::remove (pbegin, pend, 20); // 10 30 30 10 10 ? ? ?
// ^ ^
std::cout << "range contains:";
for (int* p=pbegin; p!=pend; ++p)
std::cout << ' ' << *p;
std::cout << '\n';
return 0;
}
Strictly speaking, the posted example code could be optimized to not need the pointers (especially if you're using any standard container types like a std::vector), and there's also the std::remove_if function which allows for additional parameters to be passed for more complex predicate logic.
To that however, you made mention of the Cut the sticks challenge, which I don't believe you actually need to make use of any remove functions (beyond normal container/array remove functionality). Instead, you could use something like the following code to 'cut' and 'remove' according to the conditions set in the challenge (i.e. cut X from stick, then remove if < 0 and print how many cuts made on each pass):
#include <iostream>
#include <vector>
int main () {
// this is just here to push some numbers on the vector (non-C++11)
int arr[] = {10,20,30,30,20,10,10,20}; // 8 entries
int arsz = sizeof(arr) / sizeof(int);
std::vector<int> vals;
for (int i = 0; i < arsz; ++i) { vals.push_back(arr[i]); }
std::vector<int>::iterator beg = vals.begin();
unsigned int cut_len = 2;
unsigned int cut = 0;
std::cout << cut_len << std::endl;
while (vals.size() > 0) {
cut = 0;
beg = vals.begin();
while (beg != vals.end()) {
*beg -= cut_len;
if (*beg <= 0) {
vals.erase(beg--);
++cut;
}
++beg;
}
std::cout << cut << std::endl;
}
return 0;
}
Hope that can help.
If you have no space bound try something like that,
lets array is A and number is number.
create a new array B
traverse full A and add element A[i] to B[j] only if A[i] != number
assign B to A
Now A have no number element and valid size is j.
Check this:
#define N 5
int main()
{
int ar[N] = {0,1,2,1,0};
int tar[N];
int keyEle = 0;
int newN = 0;
for(int i=0;i<N;i++){
if (ar[i] != keyEle) {
tar[newN] = ar[i];
newN++;
}
}
cout<<"Elements after deleteing key element 0: ";
for(int i=0;i<newN;i++){
ar[i] = tar[i];
cout << ar[i]<<"\t" ;
}
}
Unless there is a need to use ordinary int arrays, I'd suggest using either a std::vector or std::array, then using std::remove_if. See similar.
untested example (with c++11 lambda):
#include <algorithm>
#include <vector>
// ...
std::vector<int> arr;
// populate array somehow
arr.erase(
std::remove_if(arr.begin(), arr.end()
,[](int x){ return (x == 0); } )
, arr.end());
Solution to Cut the sticks problem:
#include <climits>
#include <iostream>
#include <vector>
using namespace std;
// Cuts the sticks by size of stick with minimum length.
void cut(vector<int> &arr) {
// Calculate length of smallest stick.
int min_length = INT_MAX;
for (size_t i = 0; i < arr.size(); i++)
{
if (min_length > arr[i])
min_length = arr[i];
}
// source_i: Index of stick in existing vector.
// target_i: Index of same stick in new vector.
size_t target_i = 0;
for (size_t source_i = 0; source_i < arr.size(); source_i++)
{
arr[source_i] -= min_length;
if (arr[source_i] > 0)
arr[target_i++] = arr[source_i];
}
// Remove superfluous elements from the vector.
arr.resize(target_i);
}
int main() {
// Read the input.
int n;
cin >> n;
vector<int> arr(n);
for (int arr_i = 0; arr_i < n; arr_i++) {
cin >> arr[arr_i];
}
// Loop until vector is non-empty.
do {
cout << arr.size() << endl;
cut(arr);
} while (!arr.empty());
return 0;
}
With a single loop:
if(condition)
{
for(loop through array)
{
if(array[i] == 0)
{
array[i] = array[i+1]; // Check if array[i+1] is not 0
print (array[i]);
}
else
{
print (array[i]);
}
}
}
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
I want to remove similar elements from 2 vectors (or list) . I found a similar question here, he used <algorimth> to solve the problem. My question is is the any other approaches without using <algorimth>?
Mine is I create a vector to save the indices of the common elements, then delete the elements have the 'tagged' index. Wild idea though, this ain't work.
An example :
Vector A={1,2,3,4,5};
Vector B={2,3,4,6};
Vector result={1,5};
Here is a solution with lists that already takes care to SORT and UNIQUE the input.
//
#include "stdafx.h"
#include <list>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int A_arrey[] = { 1, 2, 4, 5, 7, 8 };
int B_arrey[] = { 1, 2, 3, 5, 6, 8, 9 };
list<int> A_list(A_arrey, A_arrey + 6);
list<int> B_list(B_arrey, B_arrey + 7);
A_list.sort();
A_list.unique();
B_list.sort();
B_list.unique();
for (int i = 0; i < sizeof(A_arrey) / sizeof(A_arrey[0]); i++)
B_list.remove(A_arrey[i]);
for (int i = 0; i < sizeof(B_arrey) / sizeof(B_arrey[0]); i++)
A_list.remove(B_arrey[i]);
A_list.merge(B_list);
cout << "My list contains:";
for (list<int>::iterator it = A_list.begin(); it != A_list.end(); it++)
std::cout << ' ' << *it;
cout << '\n';
}
In a case where all values are unique and sorted, the following would work:
#include <iostream>
#include <vector>
using namespace std;
vector<int> A={1,2,3,4,5};
vector<int> B={2,3,4,6};
vector<int> result;
int main()
{
int a = 0;
int b = 0;
while(a < A.size() && b < B.size())
{
/* Same value - skip to next on both sides */
if (A[a] == B[b])
{
a++;
b++;
}
else
/* Smaller value is unique, so push back that */
if (A[a] < B[b])
{
result.push_back(A[a]);
a++;
}
else
{
result.push_back(B[b]);
b++;
}
}
while (a < A.size())
{
result.push_back(A[a]);
a++;
}
while (b < B.size())
{
result.push_back(B[b]);
b++;
}
for(auto r : result)
{
cout << r << ", ";
}
cout << endl;
return 0;
}
There are a number of other methods. If the values aren't enormous, one could use an array to count up when you encounter the value in A, then count down for B, and then go through the array of counters when finished to give a list of unique values.
Edit: Updated with complete code that "works".
I think you need something like this:
vector<T> v(SIZE);
T tmp=v[0];
// ... Fill your vector here
for(int i=0;i<SIZE;++i)
v[i]==tmp?v.erase(i):tmp=v[i];