Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ arrays with unknown size

Tags:

c++

arrays

I'm trying to implement a program which gives you a sequence with a determined start, end and base, problem is that i cannot determine what will be the number of elements

this is my code for a simple arithmetic progression generator

float Arithmetic_squence[](float start, float end, float b) {
  float result[];
  float last_number = start;
  while (last_number <= (end - b)) {
    result[sizeof(result)] = last_number;
    last_number += b;
  }
}

it won't compile because it wants a size

i also want the code as simple as possible so i wish i won't have to implement a non-efficient, time consuming linked list

i also don't know how to deal with vectors, maybe if there's a quick guide i may use it

like image 764
Ahmed Nematallah Avatar asked Dec 21 '22 03:12

Ahmed Nematallah


2 Answers

Yes, use std::vector, the standard library implementation of a runtime-resizeable array:

vector<float> Arithmetic_squence(float start, float end, float b) {
  vector<float> result;

  float last_number = start;

  while (last_number <= (end - b)) {
    result.push_back(last_number);
    last_number += b;
  }

  return result;
}

The vector named result starts out empty and adds elements each time you do push_back.

You can get the number of elements in a vector with the size() member function:

vector<float> f = Arithmetic_squence(x, y, z);

for (int i = 0; i < f.size(); ++i)
    cout << f[i] << endl;

vector becomes a very powerful tool when you learn the ins and outs of the Standard Library (iterators, algorithms, etc); see http://en.cppreference.com/w/cpp/container/vector for a reference to std::vector, and http://en.cppreference.com/w/cpp/ for a general C++ Standard Library reference, up to date with the C++11 standard.

like image 57
Seth Carnegie Avatar answered Dec 24 '22 03:12

Seth Carnegie


Using std::vector[tutorial] would be best in this case:

#include <vector>

std::vector<float> Arithmetic_squence(float start, float end, float b) {
  std::vector<float> result;
  float last_number = start;

  while (last_number <= (end - b)) {
    result.push_back(last_number);
    last_number += b;
  }

  return result;
}
like image 27
Tim Cooper Avatar answered Dec 24 '22 01:12

Tim Cooper