Concatenation of vectors [duplicate] - c++

This question already has answers here:
Appending a vector to a vector [duplicate]
(4 answers)
Closed 9 years ago.
My apologies for the title, I did not know of a better one.
So, basically, I have a 1D vector, which I extract 256 pieces of data from this, until there is no more data left.
std::size_t begin = 0;
std::size_t nextEnd = 0;
while (nextEnd < signal.size()) {
begin = nextEnd;
nextEnd += 256;
Transform(signal, begin, std::min(nextEnd, signal.size()));
}
Inside the "Transform" function, there is a new, temp vector created called temp_vector and inside my main I have a global 1D vector.
What I want to do is, every iteration of this loop, the values of the temp_vector is pushed back into the global 1D vector at the right position.
So for example:
std::vector<double> global;
std::vector<double> actual = {1,1,0,0,2, 3, 4 ....., n};
// here loop over n number of elements
// TRANSFORM:
// std::vector<double> temp_vector = {10, 50}; // after calculations
// global.push_back(temp_vector);
So at the end result, the global_vector will still be a 1D vector, however, will contain all of the values, in the same place for each of the elements.
I hope I have explained myself enough!

Here is code for array merging:
#include <vector>
#include <iostream>
int main() {
std::vector<int> glob = {1, 2, 3};
std::vector<int> temp_vector = {4, 5, 6};
glob.insert(glob.end(), temp_vector.begin(), temp_vector.end());
std::vector<int>::const_iterator it = glob.begin();
for(; it != glob.end(); ++it) {
std::cout << *it << ", ";
}
return 0;
}
Output:
./a.out
1, 2, 3, 4, 5, 6,

Consider to use an ordered container like std::set or std::priority_queue and insert into that container directly, not using a temporary.

Related

initialize 2d vector in c++

So, I have the following code in c++:
This is the 2d vector:
vector<vector<int>> adj;
Initialization of 2d vector:
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(3);
adj[1].push_back(4);
adj[1].push_back(5);
Printing the vector:
for(auto i : adj) {
for(auto j : i)
cout << j << " ";
cout << endl;
}
Compilation is without error but when I try to run it shows nothing.
How to fix this?
When you write adj[0], you're implicitly assuming that the vector has a size of at least 1, in order for the zeroth element to exist. This is not the case for an empty vector, such as a newly initialized one. Unfortunately, this does not guarantee an error of any kind, it is Undefined Behavior, and the compiler is allowed to let literally anything happen. To avoid it, you need to make room for those elements, which can be done in a number of ways:
adj.resize(2); // now size == 2, and [0] and [1] can be safely accessed
adj[0].push_back(1);
adj[1].push_back(3);
or alternatively
adj.push_back({}); // append default-constructed vector
adj.back().push_back(1); // append 1 to the above vector
or, perhaps most concisely:
adj = {
{1, 2},
{3, 4, 5}
};
// adj now contains two vectors containing {1, 2} and {3, 4, 5} respectively
If you want to use the subscript [] operator for indexed access to a vector, consider using vector.at(), which performs the same functionality but throws an exception if the index is out of range. This can be very helpful for debugging.
You can initialize the size of the vector by calling its constructor:
vector< vector<int> > adj(row_size, vector<int>(col_size));
^^^ ^^^^^^^ ^^^
Dimension 1 Element Ctor Dimension 2
Then you can index it like an array.
std::vector operator[] expects an element to exist. It will result in undefined behavior if an undefined element is accessed. Push a std::vector to the outer vector before pushing int to the inner vector. The at() member can be used to safely access any array index with error handling.
#include <vector>
#include <iostream>
int main()
{
std::vector<std::vector<int>> adj(2); // add two std::vector<int>
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(3);
adj[1].push_back(4);
adj[1].push_back(5);
for(auto const & i : adj) {
for(auto const & j : i)
std::cout << j << " ";
std::cout << std::endl;
}
}

How to safely insert an element into an array c++?

I have a simple program to add an element to an array:
void printArray(int inp[], int size)
{
cout << "[";
for (int i = 0; i < size - 1; i++)
{
cout << inp[i] << ", ";
}
cout << inp[size - 1] << "]" << endl;
}
int addElement(int inputArray[], int inputSize, int element, int atIndex)
{
int cur = inputSize;
while (cur >= 0)
{
if (cur == atIndex)
{
inputArray[cur] = element;
return inputSize + 1;
}
inputArray[cur] = inputArray[cur - 1];
cur--;
}
return inputSize + 1;
}
int arr1[] = {1, 5, 9, 2};
int arr2[] = {1, 5, 9, 2};
int main()
{
int arraySize = sizeof(arr1) / sizeof(arr1[0]);
addElement(arr1, arraySize, 7, 0);
printArray(arr1, arraySize + 1);
printArray(arr2, arraySize);
return 0;
}
This outputs:
[7, 1, 5, 9, 2] [2, 5, 9, 2]
Even though I haven't touched arr2 it is modified. I think because arr1 and arr2 are allocated contiguously in memory, and naively adding an element to arr1 overwrites arr2[0].
How should I handle this case and add only if the next space is unused, otherwise move the entire array to another location?
You can achieve this easily by using std::vector.
It has a method called insert, where you just pass a position and a number as arguments and it will handle the reallocation by itself.
For example: if you write:
vector<int> vec = { 1, 2, 3, 4, 5 };
vec.insert(vec.begin() + 2, 100);
Now elements in your vector are 1, 2, 100, 3, 4, 5.
I don't know if this will help you, but you can also add multiple elements at once:
vector<int> vec = { 1, 2, 3, 4, 5 };
vec.insert(vec.begin() + 3, { 100, 101 });
Now elements in your vector are: 1, 2, 3, 100, 101, 4, 5.
As you can see, the first argument is the position of the first inserted element and the second one is element or list of elements that you want to insert.
You can read more about std::vector here and about std::vector::insert here
Hope this helps.
As what the comments mentioned by #StoryTeller, you can use a std::vector.
But you have to pick on which function of the container you wanna use, there are 2 types.
::insert, which inserts data on the specific location in the
container. This is iterator based.
::push_back, which inserts at the back/last of the container
You can use any of them, depending on your purpose, just be sure of ::insert that you are pointing to the correct position(iterator wise).
Also, as of C++11 you can use ::emplace and ::emplace_back, which constructs and inserts data. You can find more at,
http://www.cplusplus.com/reference/vector/vector/
Hope this helps.
I have a simple program to add an element to an array:
Impossible. An array's size is fixed at compile time. In other words,
int arr1[] = {1, 5, 9, 2};
is a lot like:
int arr1_1 = 1;
int arr1_2 = 5;
int arr1_3 = 9;
int arr1_4 = 2;
I think it is helpful, for learning purposes, to view an array like this, and not like a container which can shrink and grow while the program is running. Adding an element to an array at runtime would be like asking to add a variable at runtime. C++ arrays don't work like that.
You can use new[] to set an array's initial size at runtime, but even then you cannot "add" anything. In fact, don't use new[], ever.
Go to cppreference.com, learn about std::vector and relearn everything from scratch. Start with the example code at the bottom of the page.

creating a two dimensional std::vector

I want to create a two-dimensional vector where the first dimension is constant by the second dimension is different, for example
int const mysize = 3;
int vecSizes[3] = {7, 2, 10};
vector<vector<int>> out_buff(mysize);
I want my inner vectors to be according to the sizes in vecSizes as the following
out_buff[0] // has size 7
out_buff[1] // has size 2
out_buff[2] // has size 10
I do not want to use push_back or resize because it takes time when using large vectors, is there a way to do that?
Elements in a std::vector have to be constructed, so in order to create the vectors of the size you want, you will have to use push_back or resize (preferably resize because it only will perform 1 allocation)
One alternative could be instead of actually changing the size, just calling reserve, which just allocates memory but doesn't actually insert any elements. The reported size will still be zero, but capacity will return at least what was passed to reserve.
Here is a complete program with minor modifications to OP's code. Note the assertions (i.e. verifications) of the sizes and capacities.
#include <vector>
#include <cassert>
using namespace std;
int main() {
enum {N = 3};
int const vecSizes[N] = {7, 2, 10};
vector<vector<int>> out_buff{N};
assert(out_buff.size() == N);
assert(out_buff.capacity() == N);
for (int i = 0; i != N; ++i) {
out_buff.at(i).reserve(vecSizes[i]);
}
int i = 0;
for (auto const& vec : out_buff) {
assert(vec.size() == 0);
assert(vec.capacity() == vecSizes[i++]);
}
}
Live example: http://ideone.com/ikm1LR

how to get size of array from array of arrays in c++ [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 7 years ago.
I want help on the following code
int arr_1[] = {1, 2, 3, 4, 5};
int arr_2[] = {6, 7, 8};
int arr_3[] = {9, 10};
int* arr[] = {arr_1, arr_2, arr_3, NULL};
// print all the elements in array of arrays
// printArray(arr);
cout << sizeof arr_1;
cout << sizeof *arr;
when I try the first cout, it gives me 20, which is correct.
but when i try the second cout, it gives me 8 which is size of a pointer variable
why. !!
could anyone give me a correct explanation and how can i get the correct size in the second way i.e from array of arrays.
Thanks in advance
To count the number of elements in a static array, you can create a template function:
template < typename T, size_t N >
size_t countof( T const (&array)[ N ] )
{
return N;
}
For standard containers such as std::vector, the size() function is used. This pattern is also used with boost arrays, which are fixed size arrays and claim no worse performance to static arrays. The code you have in a comment above should be:
for ( std::vector::size_type i(0); i < entries.size(); ++i )

How to remove the elements of an array within a certain range

I have a one-dimensional array of size 10. I want to remove the elements from 5 to 8. Can somebody give me an example of how to do it? This is how I defined my array but I have no idea about how to start.
#include <iostream>
#include <iomanip>
using namespace std;
int array[10] = {1,2,3,4,5,6,7,8,9,10};
So, the output should be 1,2,3,4,5,10. (index 0 = element 1)
Thanks
An alternative to arrays is to use a vector. In this case you can do:
#include <vector>
// create vector for integers
std::vector<int> v;
// set values from 1 to 10
for (int i=1; i<=10; i++)
v.push_back(i);
// erase from 5 to 8
v.erase (v.begin()+5, v.begin()+9);
BTW, if your compiler supports C++11, you can initialize your vector as:
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
In the above case, its an array of 10 elements array[10]. As the array size is fixed, it may not be possible to remove an item from the array.
Rather, you can assign null or someother value to the corresponding element.
BTW, I would rather use, std::list or std:: vector instead of array.
Anyhow, If you mean to get rid of that element, you'd need to shift all the ones to the right of that element one to the left:
for (int i = index; i < /* length */; i++)
array[index] = array[index+1];
array[length-1] = 0;
You can't literally remove them because C++'s built-in arrays (like C's) are fixed-size.
What you can do is overwrite them with the values that come after them, and then (if you want to) zero out the four now-extra positions at the end of the array. e.g.:
// copy latter values over the values we don't want
for (int i=4; i<6; i++) array[i] = array[i+4];
// zero out the no-longer-necessary values at the end, just so they won't appear valid anymore
for (int i=6; i<10; i++) array[i] = 0;
and then when printing the array, print only the first 6 values rather than all 10, since your array is (conceptually, even if not actually) "shorter" now.
Not sure what exactly you want your output to be, so I'm just providing another possible solution here:
// your input
int array[10] = {1,2,3,4,5,6,7,8,9,10};
// 1. put all invalid element in the back of the array
// "it" points to the first invalid element
int* it = std::remove_if(std::begin(array), std::end(array),
[](int e)
{
return (e >= 5) && (e <= 8);
});
// 2. then, mark them as -1 (from "it" to the last element)
std::transform(it, std::end(array), it,
[](int e) -> int
{
return -1;
});
// now the array contains:
// {1,2,3,4,9,10,-1,-1,-1,-1}