I have an array and a for loop. I want the for loop to stop depending on the number of elements the array has.
For example if I have an int array []={1,0,1,0,1}
I want the loop to execute code 5 times. Similar to the function for strings .length() but for integers. An example with a simple code would be the best answer :)
like this pseudocode:
for(int b=0;b<array-length;b++)
Unless you need the index, the following works fine:
int ar[] = { 1, 2, 3, 4, 5 };
for (auto i : ar) {
std::cout << i << std::endl;
}
Since the question is tagged with C++, I'll have to suggest std::vector as the best solution. (Also for the future)
Look into this: std::vector
So for you this'd be like the following:
std::vector<int> array {1,0,1,0,1};
for(int i = 0; i < array.size(); i++)
...
Or in the worst case an std::array if you don't want the features of a vector.
See also: std::array
To find length of an array, use this code
int array[5];
std::cout << "Length of array = " << (sizeof(array)/sizeof(*array)) << std::endl;
So in your case, it will be for example:
int array[5];
for(int b=0; b < sizeof(array)/sizeof(*array); b++){
std::cout << array[b] << std::endl;
}
Related
Let's say I have a vector of integers:
vector<int> v(n);
Which I fill up in a for loop with valid values. What I want to do is to find a index of a given value in this vector. For example if I have a vector of 1, 2, 3, 4 and a value of 2, i'd get a index = 1. The algorithm would assume that the vector is sorted in ascending order, it would check a middle number and then depending of it's value (if its bigger or smaller than the one we're asking for) it would check one of halves of the vector. I was asked to do this recursive and using pointer. So I wrote a void function like:
void findGiven(vector<int> &v){
int i = 0;
int *wsk = &v[i];
}
and I can easily access 0th element of the vector. However I seem to have some basic knowledge lacks, because I can't really put this in a for loop to print all the values. I wanted to do something like this:
for (int j = 0; j<v.size(); j++){
cout << *wsk[j];
}
Is there a way of doing such a thing? Also I know it's recurisve, I'm just trying to figure out how to use pointers properly and how to prepare the algorithm so that later I can build it recursively. Thanks in advance!
The correct way is:
for (int wsk : v) {
cout << wsk;
}
If you insist on pointers:
int* first = v.data();
for (size_t j = 0; j < v.size(); ++j) {
cout << first[j];
}
My code is to extract odd number and even number in an 1D array.
#include <iostream>
using namespace std;
int main() {
int a[6] = {1,6,3,8,5,10};
int odd[]={};
int even[]={};
for (int i=0; i < 6; i++) {
cin >> a[i];
}
for (int i=0; i < 6; i++) {
if (a[i] % 2 == 1) {
odd[i] = a[i];
cout << odd[i] << endl;
}
}
cout << " " << endl;
for (int i=0; i < 6; i++) {
if (a[i] % 2 == 0) {
even[i] = a[i];
cout << even[i] << endl;
}
}
return 0;
}
the output is:
1
3
5
2
1
6
It shows that it successfully extract odd numbers but the same method applied to the even number. It comes with an issue while the even number is 4.
Could anyone help me find the cause here? Thanks.
You've got an Undefined Behavior, so result may be any, even random, even formatted hard drive.
int odd[] = {} is the same as int odd[/*count of elements inside {}*/] = {/*nothing*/}, so it's int odd[0];
Result is not defined when you're accessing elements besides the end of array.
You probably have to think about correct odd/even arrays size, or use another auto-sizeable data structure.
First, although not causing a problem, you initialize an array with data and then overwrite it. The code
int a[6] = {1,6,3,8,5,10};
can be replaced with
int a[6];
Also, as stated in the comments,
int odd[]={};
isn't valid. You should either allocate a buffer as big as the main buffer (6 ints) or use a vector (although I personally prefer c-style arrays for small sizes, because they avoid heap allocations and extra complexity). With the full-size buffer technique, you need a value like -1 (assuming you intend to only input positive numbers) to store after the list of values in the arrays to tell your output code to stop reading, or store the sizes somewhere. This is to prevent reading values that haven't been set.
I don't understand your problem when 4 is in the input. Your code looks fine except for your arrays.
You can use std::vector< int > odd; and then call only odd.push_back(elem) whem elem is odd.
I am fairly new to c++, is there a way in c++ through which we can cout a whole static array apart from iterating via a for loop?
int arra[10] = {1,2,3,4};
std::cout << arra << std::endl;
I tried this but, this is printing address of the first element in the array.
Following doesn't use (explicitly) loop:
std::copy(std::begin(arra),
std::end(arra),
std::ostream_iterator<int>(std::cout, "\n"));
but loop seems simpler to read/write/understand:
for (const auto& e : arra) {
std::cout << e << std::endl;
}
#include<iostream>
using namespace std;
int main(){
int i;
int myarr[5]={9,84,7,55,6};
for(i=0;i<5;i++){
cout<<myarr[i]<<endl;
}
}
Some how you are going to have to visit each element of the array to display the contents. This can be done long form or use a loop. Fortunately we can use std::copy to fide the loop and display the array.
int arr[] = {1,2,3,4,5};
std::copy(std::begin(arr), std::end(arr), std::ostream_iterator<int>(std::cout, " "));
Live Example
You need to either loop over the array
int arra[10] = {1,2,3,4};
for (int i = 0; i<sizeof(arra)/sizeof(arra[0]); ++i)
{
std::cout << arra[i] << std::endl;
}
or use
std::copy(std::begin(arra), std::end(arra), std::ostream_iterator<int>(std::cout,"\n"));
As you asked to do this without an Array, you could easily do this:
std::copy(arra, arra + 10,
std::ostream_iterator<int>(cout, "\n"));
If you want to write good code, you could use std::array and then simply write arra.begin() and arra.end().
There are basically two ways. First one is a loop somewhere . The loop can be explicit - in your code - or it can be implicit through library. Example of library loop:
std::for_each(cbegin(arra), cend(arra), [](int i) {std::cout << "i ";});
The second way of printing the array is with the use of recursion. Here is example of the code:
void print_element(const int* head, const int* tail) {
if (head == tail)
return;
std::cout << *head << " ";
print_element(head + 1, tail);
}
....
print_element(arr, arr + sizeof(arr) / sizeof(*arr));
Couple of words about recursion solution. Depending on your optimization, it can produce different results. Performance of the recursion will be roughly equivalent to the performance of the loop on any optimization level with AMD64 ABI. The reason for that is that arguments to functions are passed through registers (not pushed into stack), and the frame pointers are not used with any optimization. With this in mind, the only CALL/RET (which push/pop RIP) will slow down execution compared the loop, but this degradation is not measurable. The real issue, however, is that there is limited number of recursed calls which can be made on a given system (usually around single thousands), so printing an array of 1000000 elements is guaranteed to crash the application.
With higher levels of optimization which involve tail-call optimization, the recursion calls will be translated into plain jmps and the performance will be exactly the same as one with the loop. It will also eliminate the problem of maximum recursion level - so that arrays of any sizes can be printed.
It is printing address because you are pointing to an array, not its elements.
try this-
void printArray(int arr[], int n)
/* n is size here*/
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
i am currently trying to learn some C++ and now i got stuck in an exercise with vectors. So the task is to read ints from a text file and store them in the vector which should be dynamic.
I guess there is something wrong with the while-loop?
If I start this, the program fails and if I set the vector size to 6, I get
6 0 0 0 0 0 as output.
Thanks for any hints.
int main()
{
const string filename = "test.txt";
int s = 0;
fstream f;
f.open(filename, ios::in);
vector<int> v;
if (f){
while(f >> s){
int i = 0;
v[i] = s;
i = i+1;
}
f.close();
}
for(int i = 0; i < 6; i++){
cout << v[i] << "\n";
}
}
You don't grow the vector. It is empty and cannot hold any ints. You'll need to either resize it every time you want to add another int or you use push_back which automatically enlarges the vector.
You set i = 0 for every iteration so you would change the first value of the vector every iteration instead of the next one.
Go for:
v.push_back(s);
in your loop and
for(int i = 0; i < v.size(); i++) { // ...
Remark:
You normally don't hardcode vector sizes/bounds. One major point about using std::vector is its ability to behave dynamically with respect to its size. Thus, the code dealing with vectors should not impose any restrictions about the size of the vector onto the respective object.
Example:
for(int i = 0; i < 6; i++){ cout << v[i] << "\n"; }
requires the vector to have at least 6 elements, otherwise (less than 6 ints) you access values out of bounds (and you potentially miss elements if v contains more than 6 values).
Use either
for(int i = 0; i < v.size(); i++){ cout << v[i] << "\n"; }
or
for(std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i)
{
cout << *i << "\n";
}
or
for(auto i = v.begin(); i != v.end(); ++i)
{
cout << *i << "\n";
}
or
for(int x : v){ cout << x << "\n"; }
or
for(auto && x : v){ cout << x << "\n"; }
or
std::for_each(v.begin(), v.end(), [](int x){ std::cout << x << "\n"; });
or variants of the above which possibly pre-store v.size() or v.end()
or whatever you like as long as you don't impose any restriction on the dynamic size of your vector.
The issue is in the line i= 0. Fixing that will give an issue in the line v[i] = s.
You always initialise i to 0 in the while loop, and that is responsible for the current output. You should shift it out of the while loop.
After fixing that, you have not allocated memory to that vector, and so v[i] doesn't make sense as it would access memory beyond bounds. This will give a segmentation fault. Instead, it should be v.push_back(i), as that adds elements to the end of a vector, and also allocates memory if needed.
If you are using std::vector you can use v.push_back(i) to fill this vector
Error is this line int i = 0;
because you declare i=0 every time in while-loop.
To correct this move this line outside from loop.
Note: this will work, if you declare v like normal array for example int v[101]
When you use std vectors you can just push element at the end of vector with v.push_back(element);
v[i] = s; //error,you dont malloc room for vector
change into : v.push_back(s);
I want to reuse a std::vector within a for loop. However, I need the vector to be empty for each iteration step of the for loop.
Question: How can I empty a vector rapidly without changing its capacity in the most efficient way?
What I used so far is
std::vector<int> myVec;
for(int i=0; i<A_BIG_NUMBER; ++i) {
std::vector<T>().swap(myVec);
myVec.reserve(STANDARD_MAXIMUM);
/// .. doing business
}
Cheers!
Solution:
Thanks for the answers, here is how I implemented (checked) it:
#include <vector>
#include <iostream>
int main() {
int n = 10;
std::vector< int > myVec;
myVec.reserve(n);
for(int j=0; j<3; ++j) {
myVec.clear();
for(int i=0; i<n; ++i) {
myVec.push_back(i);
}
for(int i=0; i<myVec.size(); ++i) {
std::cout << i << ": " << myVec[i] << std::endl;
}
}
return 0;
}
EDIT: changed from operator[] to push_back.
Use vector::clear method. It will clear the content without reducing its capacity.
myVec.clear();
This is equivalent to myVec.erase(myVec.begin(), myVec.end()).
To retain the current size of a vector with default values for its content, you can assign default values to the vector. In the case of a vector of ints, you can do the following:
myVec.assign( myVec.size(), 0 );
use clear method as below:
std::vector<int> myVec;
for(int i=0; i<A_BIG_NUMBER; ++i)
{
std::vector<T>().swap(myVec);
myVec.reserve(STANDARD_MAXIMUM);
/// .. doing business
myVec.clear();
}
Answer based on OP's solution:
The normal approach for containers is to start with an empty container and fill it up as needed with an exception for std::vector where you can reserve space eventhough there are still no objects in the container.
If you want a different approach where an "empty container" would be a container of default objects that you can access like an array (only works with std::vector and std::deque), then you need to start with resize() and you can "clean up" with fill:
int n = 10;
std::vector<int> myVec;
myVec.resize(n);
myVec[4] = 5;
std::cout << myVec[4] << "\n";
std::fill(myVec.begin(), myVec.end(), int()); // ofcourse for int, you can use 0 instead of int()
std::cout << myVec[4] << "\n";