1

I want to add the numbers of the array {1, 2, 3} to the array {7, 4, 6} so I can get an array {8, 6, 9} like this:

int main(){
    int arr[] = {1, 2, 3};
    int arr2[] = {7, 4, 6};
    arr += arr2; // invalid operands of types ‘int [3]’ and ‘int*’ to binary ‘operator+’
}
3
  • 2
    What language are you using, C or C++? Only tag the language that you are actually using. Commented Dec 8, 2021 at 14:56
  • C doesn’t provide operators that operate on whole arrays. You have to write the code yourself. Commented Dec 8, 2021 at 14:58
  • 6
    Using the standard algorithms library, std::transform(std::cbegin(arr), std::cend(arr), std::cbegin(arr2), std::begin(arr), std::plus<>{}); Commented Dec 8, 2021 at 15:03

4 Answers 4

10

std::valarray allows you to do this, with some minor changes to your code:

#include <iostream>
#include <valarray>

int main() {
    std::valarray<int> arr{1, 2, 3};
    std::valarray<int> arr2{7, 4, 6};
    arr += arr2;        
    std::cout << arr[0] << arr[1] << arr[2];   
}

Compared to the other C++ standard library containers, std::valarray is equipped with a fair number of "bulk" mathematical operations.

Sign up to request clarification or add additional context in comments.

Comments

4

If the arrays are "fixed" at compile time using a constexpr function is also a good idea:

#include <array>
#include <iostream>

//
// Define an add function template
// 
// This will provide compile time checking of equal array sizes 
// so we have no need to check that condition at runtime (over and over again).
// 
// By making it constexpr we can also use this function's results at compile time (See below).
// Also by using std::array you have a good example on how C++ can return
// arrays from functions.
//
// template makes the code reusable for multiple types and array sizes.
//
// typename type_t makes this function usable for all kinds of types so it isn't restricted to ints
// std::size_t N allows for the compiler to generate correct code for positive array sizes
// 
// arr1, arr2 :
// Passed as const because the add function should never change the content of those arrays.
// type_t(&arr1)[N] is C++'s way of passing an array of known size 
//     so you don't have to pass pointers, pointers to pointers and a seperate size parameter
//     Another option would be to use std::array<type_t,N>&, but this syntax for passing arrays
//     is very useful knowledge. 
//
// constexpr means, if you follow some rules you can use this function at compile time
//     which means that the compiler will compile this function and then use it too
// 
// auto return type means that you let the compiler work out what type you return
// this can help later when refactoring code. 
// 

template<typename type_t, std::size_t N>
constexpr auto add(const type_t(&arr1)[N], const type_t(&arr2)[N])
{
    // You can't return "C" style arrays from functions but you can return objects.
    // std::array is a wrapper object for arrays (with almost no overhead)
    // the extra {} at the end will initialize all values in the array to default value for type_t (0 for ints)
    // (one of the rules for constexpr, everything must be initialized)
    std::array<type_t, N> retval{};

    // a standard for loop 
    for (std::size_t n = 0; n < N; ++n) retval[n] = arr1[n] + arr2[n];

    // return the array, since we return a std::array<type_t,N> that will also
    // become the return type of the function (auto)
    return retval;
}

int main()
{
    // constexpr initialization allows these arrays to be used at compile time.
    constexpr int arr[] = { 1, 2, 3 };
    constexpr int arr2[] = { 7, 4, 6 };

    // with constexpr ask the compiler to run add at compile time
    // (if the rules for constepxr in add do not fully apply then
    // the code will still be executed at runtime)
    constexpr auto result = add(arr, arr2);

    // static_assert, is like assert but then evaluated at compile time.
    // if the assert fails then teh code will not compile.
    static_assert(result[0] == 8);
    static_assert(result[1] == 6);
    static_assert(result[2] == 9);

    // to show you can use the results at runtime too
    bool comma{ false };

    // this is a range based for loop
    // using range based for loops ensures you never run out of the
    // bounds of an array (reduces bugs)
    //
    // const auto &
    // When looping over all the elements of the array
    // value will be a const reference to the current element 
    // visited. 
    // a reference to avoid copying data (not so important for ints, but important for 
    // more complex datatypes)
    // const because we are only using it, not modifying it.
    for (const auto& value : result)
    {
        if (comma) std::cout << ", ";
        std::cout << value;
        comma = true;
    }

    return 0;
}

6 Comments

not sure if this is not far beyond OPs level (templates? passing arrays by reference? constexpr? std::array? ...) maybe more explaination would be good
@463035818_is_not_a_number: I quite like this - remember that answers do not necessarily need to be targeted at the OP.
@Bathsheba i do remember. I like the answer. Though I think also others looking for a way to add elements of two arrays would be glad about more explanation ;)
@463035818_is_not_a_number: Yes, you do have a point.
though a constexpr wine celllar would be sad
|
2

You're going to want another array to store your values, we'll call this arr3 and make it the same size as the other arrays.

int arr[] = { 1,2,3 };
int arr2[] = { 7,4,6 };
int arr3[3]{};

Then you're going to want to add values from arr and arr2 and put them in arr3

arr3[0] = arr[0] + arr2[0];
arr3[1] = arr[1] + arr2[1];
arr3[2] = arr[2] + arr2[2];

You could also do this easily with a loop.

for (int i = 0; i < 3; i++)
{
    arr3[i] = arr[i] + arr2[i];
}

1 Comment

Instead of hardcoding the size of the array, I recommend using something like std::size(arr).
2

As you get more involved with vectors and matrices, you might want to consider using a proper algebra library like Armadillo. On Ubuntu you would just add

apt get install libarmadillo-dev

Then on your CMakeLists.txt

project(arma)
cmake_minimum_required( VERSION 3.0 )
find_package( Armadillo REQUIRED )
include_directories( ${ARMADILLO_INCLUDE_DIR} )
add_executable( testarma testarma.cpp )

And use it on your code

#include <armadillo>
#include <iostream>

int main()
{
    using vec = arma::Mat<int>;
    vec A{1, 2, 3};
    vec B{4, 5, 6};
    vec C = A + B;
    std::cout << C << std::endl;
}
$ ./testarma
   5       7        9

2 Comments

Wouldn't arma::Mat<int> be better?
Certainly. I changed the code to reflect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.