how to sum the column of a 2 dimentional array - c++

**it works at the beggining, adds 16 and 4 but then it doesn't add 2 + 3 and somehow even gets 8.
what am I doing wrong?**
I don't really understand how to count it separately
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int a = 0;
int my_vector[][2] = { {16,2}, {4, 3} };
for (int r = 0; r < 2; r++)
{
for (int c = 0; c < 2; c++)
{
std::cout << " " << my_vector[r][c] << "\t";
a = *my_vector[r] + *my_vector[c];
}
std::cout << "\n" << a;
std::cout << "\n";
} ```
[1]: https://i.stack.imgur.com/RbTcO.png

Here you dereference the first element in my_vector row r and add that to the dereferenced first element in my_vactor row c:
a = *my_vector[r] + *my_vector[c];
Then the result stored in a is overwritten in the next loop.
You probably meant:
a += my_vector[r][c]; // or: a = a + my_vector[r][c];
Another approach could be to use std::for_each and std::accumulate:
#include <algorithm> // std::for_each
#include <numeric> // std::accumulate
#include <iostream>
#include <iterator> // std::begin, std::end
int main() {
int a = 0;
int my_vector[][2] = { {16,2}, {4, 3} };
// for_each loops over the rows
std::for_each(std::begin(my_vector), std::end(my_vector), [&a](auto& row) {
// and accumulate sums up everything in columns in that row
a += std::accumulate(std::begin(row), std::end(row), 0);
});
std::cout << "\n" << a << '\n';
}

Related

How to shift values of given array by moving first value to the last C++

I was struggling on how to move the first value to the las in order like shown in the picture
enter image description here
What should I do?
#include <iostream>
using namespace std;
void rotate(int A[], int n = 5)
{
int x = A[n - 1], i;
for (i = n - 1; i > 0; i--)
{
A[i] = A[i -1];
}
A[0] = x;
}
int main()
{
int A[] = { 1, 2, 3, 4, 5 }, i;
int n = sizeof(A) / sizeof(A[5]);
cout << "Given array is \n";
for (i = 0; i < n; i++)
cout << A[i] << ' ';
for (int j = 0; j < n; j++)
{
rotate(A, n);
cout << "\nStep " << j << " --> ";
for (i = 0; i < n; i++)
{
cout << A[i] << ' ';
}
}
return 0;
}
Your code is still quite "C" like. Here is an example that hopefully will teach you some C++ coding :
#include <algorithm>
#include <iostream>
#include <vector>
// passing arrays is easier using std::vector/std::array (no need to pass size seperately)
void rotate(std::vector<int>& values)
{
// using algorithm's std::swap you can better show WHAT you are doing
// vector and array also have a size() method so you don't
// have to use "C" style sizeof tricks.
for (std::size_t n = 0; n < values.size() - 1; ++n)
{
std::swap(values[n], values[n + 1]);
}
}
int main()
{
// prefer std::vector (or std::array) in C++. Not "C" style arrays
std::vector<int> values{ 1,2,3,4,5 };
rotate(values);
// use range based for loop if you can.
for (const auto value : values)
{
std::cout << value << " ";
}
return 0;
}

Getting random numbers on vector operation c++

I'm getting weird numbers as output in this code :
#include <iostream>
#include <vector>
int main(){
std::vector<std::vector<int>> vec = {{0,1},{2,3}};
vec.push_back({4,5});
vec.push_back({5,6});
for (int i = 0; i < vec.size(); i++){
for (int i2 = 0; i2 < vec.size(); i2++){
std::cout << vec[i][i2] << std::endl;
}
}
return 0;
}
It's returning to me:
0
1
1280136264
0
2
3
347673833
38962
4
5
297276653
134256690
5
6
280499436
268474418
I just want to know how to do it properly, and why I'm getting these numbers.
The output you are seeing is due to undefined behavior in your code.
The outer vector object has 4 inner vector<int> objects added to it. Each of those inner vector<int> objects is holding 2 int values.
Your inner for loop is going out of bounds of the inner vector<int> objects, by trying to access 4 int values when there are only 2 int values available.
In your inner for loop, you need to change vec.size() to vec[i].size() instead, eg:
#include <iostream>
#include <vector>
int main(){
std::vector<std::vector<int>> vec = {{0,1},{2,3}};
vec.push_back({4,5});
vec.push_back({5,6});
for (size_t i = 0; i < vec.size(); ++i){
for (size_t i2 = 0; i2 < vec[i].size(); ++i2){
std::cout << vec[i][i2] << std::endl;
}
/* alternatively:
auto &vec2 = vec[i];
for (size_t i2 = 0; i2 < vec2.size(); ++i2){
std::cout << vec2[i2] << std::endl;
}
*/
}
return 0;
}
Online Demo
That being said, a safer way to code this is to use range-for loops instead, eg:
#include <iostream>
#include <vector>
int main(){
std::vector<std::vector<int>> vec = {{0,1},{2,3}};
vec.push_back({4,5});
vec.push_back({5,6});
for (auto &vec2 : vec){
for (auto value : vec2){
std::cout << value << std::endl;
}
}
return 0;
}
Online Demo

why can't I store values in my 2D vector by push back?

I got stuck in many problems where I was trying to store values in 2D vectors.
So I have written this simple code.
I am just storing and printing my values :
int main()
{
vector<vector<int>> vec;
vector<int> row{1,3,5,7,9,12,34,56};
int i,n,m,rs,vs;
rs=row.size();
cout<<"rs = "<<rs<<endl;
for(i=0;i<(rs/2);i++)
{
vec[i].push_back(row.at(i));
vec[i].push_back(row.at(i+4));
}
vs=vec.size();
cout<<vs<<endl;
for(n=0;n<vs;n++)
{
for(m=0;m<2;m++)
{
cout<<vec[n][m]<<" ";
}
cout<<endl;
}
return 0;
}
First you should read Why is “using namespace std;” considered bad practice?.
Declare variables when you use them and not at the beginning of your program.
The vector vec is empty at the beginning. In the loop
for(i=0;i<(rs/2);i++)
{
vec[i].push_back(row.at(i));
vec[i].push_back(row.at(i+4));
}
you are taking a reference to the i-th element in vec with
vec[i]
but this element does not exist. This is undefined behavior and can result in a segmentation fault. You can fix it by constructing the vector with the needed elements
#include <iostream>
#include <vector>
int main()
{
std::vector<int> row{1,3,5,7,9,12,34,56};
int rs = row.size();
std::vector<std::vector<int>> vec(rs / 2);
std::cout << "rs = " << rs << '\n';
for(int i = 0; i < rs / 2; ++i)
{
vec[i].push_back(row.at(i));
vec[i].push_back(row.at(i + 4));
}
int vs = vec.size();
std::cout << vs << '\n';
for(int n = 0; n < vs; ++n)
{
for(int m = 0; m < 2; ++m)
{
std::cout << vec[n][m] << " ";
}
std::cout << '\n';
}
return 0;
}
In this example the line
std::vector<std::vector<int>> vec(rs / 2);
constructs a vector containing rs / 2 default constructed elements. Alternatively you can start with an empty vector and push back elements in the loop
#include <iostream>
#include <vector>
int main()
{
std::vector<int> row{1,3,5,7,9,12,34,56};
int rs=row.size();
std::vector<std::vector<int>> vec;
std::cout << "rs = " << rs << '\n';
for(int i = 0; i < rs / 2; ++i)
{
vec.push_back({row.at(i), row.at(i+4)});
//
// is similar to:
// vec.push_back({});
// vec.back().push_back(row.at(i));
// vec.back().push_back(row.at(i+4));
//
// is similar to:
// vec.push_back({});
// vec[i].push_back(row.at(i));
// vec[i].push_back(row.at(i+4));
}
int vs = vec.size();
std::cout << vs << '\n';
for(int n = 0; n < vs; ++n)
{
for(int m = 0; m < 2; ++m)
{
std::cout << vec[n][m] << " ";
}
std::cout << '\n';
}
return 0;
}
I recommend the first solution. It's better to allocate memory for all elements and work with it instead of allocate memory in each loop iteration.

Split an array at a specific value C++

Say I have an array like this:
int arr [9] = {2,1,5,8,9,4,10,15,20}
How can you split the array at a certain value threshold? So say int 8 is our splitting value, the end result would be two separate arrays (or a 2d array if you want to give that a shot) that in this example would be arr1 [4] = {1,2,4,5} and arr2 [5] = {8,9,10,15,20}. arr1 stores all the values in arr that are below 8 and and arr2 stores all the values in arr that are 8 and above.
I haven't been able to locate sufficient documentation or examples of this being done and I think array manipulation and splitting is worth having examples of.
Use std::partition, or if you want to maintain the relative order and not sort the data, std::stable_partition.
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
int pivot = 8;
int arr [9] = {2,1,5,8,9,4,10,15,20};
// get partition point
int *pt = std::stable_partition(arr, std::end(arr), [&](int n) {return n < pivot;});
// create two vectors consisting of left and right hand side
// of partition
std::vector<int> a1(arr, pt);
std::vector<int> a2(pt, std::end(arr));
// output results
for (auto& i : a1)
std::cout << i << " ";
std::cout << '\n';
for (auto& i : a2)
std::cout << i << " ";
}
Live Example
If you can use C++11 then this is one way of using the standard library:
Using a partition_point: (edited the example from the link)
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::array<int, 9> v = {2,1,5,8,9,4,10,15,20};
auto is_lower_than_8 = [](int i){ return i < 8; };
std::partition(v.begin(), v.end(), is_lower_than_8 );
auto p = std::partition_point(v.begin(), v.end(), is_lower_than_8 );
std::cout << "Before partition:\n ";
std::vector<int> p1(v.begin(), p);
std::sort(p1.begin(), p1.end());
std::copy(p1.begin(), p1.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\nAfter partition:\n ";
std::vector<int> p2(p, v.end());
std::sort(p2.begin(), p2.end());
std::copy(p2.begin(), p2.end(), std::ostream_iterator<int>(std::cout, " "));
}
Which prints:
Before partition:
1 2 4 5
After partition:
8 9 10 15 20
I'm working on a solution with loops. This is a work in progress. Let me know what you think.
void splitarr(int arr[], int length) {
int accu = 0;
int accu2 = 0;
int splitter = rand() % 20;
for (int i = 0; i < length; i++) {
if (i != splitter) {
accu++;
}
}
int arr1[accu];
for (int i = 0; i < length; i++) {
if (i != splitter) {
arr1[i] = i;
}
}
for (int i = 0; i < length; i++) {
if (i == splitter) {
accu2++;
}
}
int arr2[accu2];
for (int i = 0; i < length; i++) {
if (i == splitter) {
arr2[i] = i;
}
}
}

c++ output increasing numbers

Hi I have an array of share prices but I only want to output them as they increase.
For example if I have 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5, etc. I only want to print 1,2,3,4.
I have tried setting a temporary max and min but still can't get it.
Now I only have this:
for(int h = 0; h < max; h++)
{
if(v3[h].getPrice() > 0)
{
ofile << v[h].getPrice() << ", ";
}
}
What you want is this
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
// Assign your vector
int a[] = {1,1,1,2,2,3,3,3,4,4,5,5,5,1,3};
vector<int> vec(a, a+15);
// Sort before calling unique
sort(vec.begin(), vec.end());
// Impose only one of each
vector<int>::iterator it;
it = unique(vec.begin(), vec.end());
vec.resize( distance(vec.begin(),it) );
// Output your vector
for( vector<int>::iterator i = vec.begin(); i!= vec.end(); ++i)
cout << (*i) << endl;
return 0;
}
Live example
The sort is necessary for unique to work.
#include <iostream>
using namespace std;
int main()
{
int a[15] = {1,1,1,2,2,2,3,3,3,4,4,4,5,5,5};
for (int i=0; i<15; i+=3)
{
cout << a[i] <<",";
}
return 0;
}
Increment the counter 3 times in the loop " for(int h=0;h < max; h+=3){} ".