std::begin ()

closed account (SECMoG1T)
Hi, can't understand why my functions here can't work yet they seem correct to me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 #include <iostream>
 #include <algorithm>
 
 void todefault(std::vector<int> &vec)
  {
    std::replace(vec.begin(), vec.end(),0, vec.size());// this ain't 
                                                               //working.
  }

  void print(int array[])
   {
     for(auto i=std::begin(array), i! =std::end(array); i++)// ain't working
           std::cout<<*i<<' ';                              // too
   }

I can't understand why they won't work yet I have used this functions for a thousand years, and now they just decided otherwise, throwing all over, I don't get it.

Thank you.
Last edited on
does replace take an int as it's third & fourth parameters? I thought you used it like this:
e.g.
std::replace (str.begin(), str.end(), 'c', 'k');

or with a predicate.
Last edited on
closed account (SECMoG1T)
@mutexe  
>int as it's third & fourth parameter

Am not quite sure, Btw I think I have ever used this function before and it used to work,replacing everything to zeros.

From your example above ? What should I do coz my vector type is int.
Last edited on
void print(int array[]) is the same as void print(int* array): arrays of unknown size decays to pointers. And std::begin/end does not work on pointers. There is simply no way to know array size after it decays to pointer.

To work with normal arrays size of which is known at compile time, you can do something like:
1
2
3
4
5
6
7
8
9
10
11
12
template<typename T, std::size_t N>
void print(T (&array)[N])
{
    for(auto i = std::begin(array); i != std::end(array); i++)
        std::cout << *i << ' ';
}

int main()
{
    int foo[5] = {1, 3, 5, 4, 2};
    print(foo);
}


replace takes parameters as (from, to, what_to_replace, replace_with_what). Two last parameters should be of the same type.
0 is of type int vec.size() is of type std::vector<int>::size_type
They both can be converted to each other, so compiler does not know what type to use.
You need to tell it what to do:
std::replace(vec.begin(), vec.end(), 0, static_cast<int>(vec.size()));
Last edited on
closed account (SECMoG1T)
Thank you @Minnippa , @JLBorges
void print(int array[]) is the same as void print(int* array[]):  I dint know this , I thought all arrays are equivalent and dint realize that std::begin () arguments must be of know size, Thanks. For the examples they're workin' Btw i will save them and try understand them, The template part takes my mind into circles , I'll try read on templates.

I also dint realize
Two last parameters should be of the same type. /// for std::replace

Thank you very much. SOLVED.
Topic archived. No new replies allowed.