unresolved identifier on .begin() and .end()? - c++

i keep getting this error "unresolved identified" on l_vector.begin() and l_vector.end, specifically on the begin and end functions, why is it not recognizing these simple vector functions?
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <vector>
#include <string>
using namespace std;
// function prototype
int FindIndexOfLargest(vector<int> l_vector);
int main()
{
int FindIndexOfLargest();
return 0;
}
//function definition
int FindIndexOfLargest(vector<int> l_vector)
{
vector<int>:: const_iterator iter;
int current_max_location = 0;
int current_max = 0;
for(iter = l_vector.begin(); iter != l_vector.end(); ++iter)
{
if(*iter > current_max)
{
current_max_location = iter;
}
return current_max;
}
}

I see a few causes for compilation failure.
int FindIndexOfLargest();
You have to pass an std::vector <int> to this function when you call it in main().
And finally, your function int FindIndexOfLargest(vector<int> l_vector) must return an int value.
An alternate way to write this function is to use std::max_element and std::distance.
std::size_t FindIndexOfLargest(const std::vector <int> &input)
{
std::vector<int>::const_iterator max_value =
std::max_element(input.cbegin(), input.cend());
if (max_value != input.cend()) {
return std::distance (input.cbegin(), max_value);
}
// Otherwise, throw an expection or return an error value here.
}

Related

How to change values of array at initialization in C++?

I want an array that have new attributed values if the value is x.
I can do that in PHP with that code:
$test = array(1=>55, 2=>66);
on above code if test[0] = 1, the new value of test[0] is going to be 55.
I want to do that in C++.
Normal C++ arrays do not have keys. There are always 0-indexed.
But we have std::map which is what PHP also use internally for key-based containers.
https://en.cppreference.com/w/cpp/container/map
You can make your own attributed values class in C++, so it has that behavior.
You can make it so the behavior is hard coded into the class. Or if you want to get fancier you can make the class having a value mapping passed in.
Here's an example with the value mapping passed into the class.
#include <cstddef>
#include <iostream>
#include <map>
#include <stdexcept>
#include <vector>
using sad_panda = std::logic_error;
using std::cout;
using std::map;
using std::size_t;
using std::vector;
namespace {
class AttributedValues {
vector<int> v;
map<int, int> attr_to_value;
public:
AttributedValues(map<int, int> mapping);
void set(size_t index, int value);
int operator[](size_t index) const;
};
AttributedValues::AttributedValues(map<int, int> mapping)
: attr_to_value{mapping}
{ }
void AttributedValues::set(size_t index, int value) {
if (index >= v.size()) {
v.resize(index+1);
}
auto iter = attr_to_value.find(value);
if (iter != attr_to_value.end()) {
value = iter->second;
}
v[index] = value;
}
int AttributedValues::operator[](size_t index) const {
if (index >= v.size()) {
throw sad_panda("AttributedValues::operator[] index out of range");
}
return v[index];
}
} // anon
int main() {
auto test = AttributedValues{{{1, 55}, {2, 66}}};
test.set(0, 1);
test.set(10, 2);
cout << test[0] << "\n";
cout << test[10] << "\n";
}

Iterator over a vector of strings,got as input from console giving segemntation fault

I have two different programs here,both of which creates a BST of strings and then checks if a given string is there in the BST.
The first program works fine when I pass the dereferencing of an iterator of the vector of strings to the find function.
But the second program fails and gives segmentation error when I take an input from the user and then pass the dereferencing of an iterator over the vector of that input string.
Why does it fail when I get an input from the user?
Working program
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include<typeinfo>
using namespace std;
int main()
{
vector<std::string> vn;
set<std::string> names;
BST<std::string> b2;
vn.push_back("AAA");
vn.push_back("BBB");
vn.push_back("CCC");
vector<std::string>::iterator vit = vn.begin();
for(; vit != vn.end(); vit++)
{
b2.insert(*vit);
names.insert(*vit);
}
vit = vn.begin();
for(; vit != vn.end(); ++vit)
{
if(*(b2.find(*vit)) != *vit)
{
cout << "Incorrect return value when finding " << *vit;
return -1;
}
}
}
Error giving program
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include<typeinfo>
using namespace std;
int main()
{
vector<std::string> vn;
set<std::string> names;
std::string cur_str;
BST<std::string> b2;
vn.push_back("AAA");
vn.push_back("BBB");
vn.push_back("CCC");
vector<std::string>::iterator vit = vn.begin();
for(; vit != vn.end(); vit++)
{
b2.insert(*vit);
names.insert(*vit);
}
std::getline(std::cin, cur_str);
vector<std::string> vn2;
vn2.push_back(cur_str);
vector<std::string>::iterator vit2 = vn2.begin();
vit = vn.begin();
for(; vit != vn.end(); ++vit)
{
if(*(b2.find(*vit2)) != *vit) (gives segmentation fault in this line)
{
cout << "Incorrect return value when finding " << *vit << endl;
return -1;
}
}
}
find function
template<typename Data> (Declared at the beginning)
iterator find(const Data& item) const
{
BSTNode<Data> * currentNode = root;
while(NULL != currentNode)
{
if(item < currentNode->data)
{
currentNode = currentNode->left;
}
else if(currentNode->data < item)
{
currentNode = currentNode->right;
}
else
{
// item == currentNode->data
return iterator(currentNode);
}
}
return end();
}
if(*(b2.find(*vit2)) != *vit) (gives segmentation fault in this line)
This mishandles the case where find doesn't find anything. If the value isn't found, find returns an iterator to one past the end of the container, which you then apply * to. Oops.

Cannot use .begin() or .end() on an array

The error reads:
request for member 'begin', 'end' in 'arr' which is non class type int[5],
unable to deduce from expression error.
My code:
#include <iostream>
using namespace std;
int main()
{
int * mypointer;
int arr[5] = {1,3,5,7,9};
mypointer = arr;
for(auto it = arr.begin(); it != arr.end(); ++it) {
cout<<*mypointer<<endl;
mypointer++;
}
return 0;
}
Arrays have no member functions as they aren't a class type. This is what the error is saying.
You can use std::begin(arr) and std::end(arr) from the <iterator> header instead. This also works with types that do have .begin() and .end() members, via overloading:
#include <array>
#include <vector>
#include <iterator>
int main()
{
int c_array[5] = {};
std::array<int, 5> cpp_array = {};
std::vector<int> cpp_dynarray(5);
auto c_array_begin = std::begin(c_array); // = c_array + 0
auto c_array_end = std::end(c_array); // = c_array + 5
auto cpp_array_begin = std::begin(cpp_array); // = cpp_array.begin()
auto cpp_array_end = std::end(cpp_array); // = cpp_array.end()
auto cpp_dynarray_begin = std::begin(cpp_dynarray); // = cpp_dynarray.begin()
auto cpp_dynarray_end = std::end(cpp_dynarray); // = cpp_dynarray.end()
}
For a standard fixed-length C array, you can just write
int c_array[] = {1,3,5,7,9}, acc = 0;
for (auto it : c_array) {
acc += it;
}
The compiler does the behind-the-scenes work, eliminating the need to create all those begin and end iterators.
In C++, arrays are not classes and therefore do not have any member methods. They do behave like pointers in some contexts. You can take advantage of this by modifying your code:
#include <iostream>
using namespace std;
int main()
{
int * mypointer;
const int SIZE = 5;
int arr[SIZE] = {1,3,5,7,9};
mypointer = arr;
for(auto it = arr; it != arr + SIZE; ++it) {
cout<<*mypointer<<endl;
mypointer++;
}
return 0;
}
Of course, this means that mypointer and it both contain the same address, so you don't need both of them.
One thing I'd like to point out for you is that you really don't have to maintain a separate int* to use in dereferencing the array elements, apart from the whole member thing others have well pointed out.
Using a more modern approach, the code is both more readable, as well as safer:
#include <iostream>
#include <algorithm>
#include <array>
#include <iterator>
using namespace std;
int main()
{
std::array<int, 5> cpp_array{1,3,5,7,9};
// Simple walk the container elements.
for( auto elem : cpp_array )
cout << elem << endl;
// Arbitrary element processing on the container.
std::for_each( begin(cpp_array), end(cpp_array), [](int& elem) {
elem *= 2; // double the element.
cout << elem << endl;
});
}
Using the lambda in the second example allows you to conveniently perform arbitrary processing on the elements, if needed. In this example, I'm just showing doubling each element, but you can do something more meaningful within the lambda body instead.
Hope this makes sense and helps.
Perhaps here is a cleaner way to do it using templates and lambdas in c++14:
Define:
template<typename Iterator, typename Funct>
void my_assign_to_each(Iterator start, Iterator stop, Funct f) {
while (start != stop) {
*start = f();
++start;
}
}
template<typename Iterator, typename Funct>
void my_read_from_each(Iterator start, Iterator stop, Funct f) {
while (start != stop) {
f(*start);
++start;
}
}
And then in main:
int x[10];
srand(time(0));
my_assign_to_each(x, x+10, [] () -> int { int rn{}; rn = rand(); return rn; });
my_read_from_each(x, x+10, [] (int value) { std::cout << value << std::endl; });
int common_value{18};
my_assign_to_each(x, x+10, [&common_value] () -> int { return common_value; });
my_read_from_each(x, x+10, [] (int value) { std::cout << value << std::endl; });
Quite late but I think it's worth to mention that:
void findavgTime(int n)
{
int wt1[n];
fill_wt(wt1,n); //Any method that puts the elements into wt1
int wt2[3];
int sum = accumulate(begin(wt1), end(wt1), 0); // Fails but wt2[3] will pass. Reason: variable-sized array type ‘int [n]’ is not a valid template argument)
}

c++ find_if lambda

What is wrong with the code below? It is supposed to find an element in the list of structs if the first of the struct's members equals to 0. The compiler complains about the lambda argument not being of type predicate.
#include <iostream>
#include <stdint.h>
#include <fstream>
#include <list>
#include <algorithm>
struct S
{
int S1;
int S2;
};
using namespace std;
int main()
{
list<S> l;
S s1;
s1.S1 = 0;
s1.S2 = 0;
S s2;
s2.S1 = 1;
s2.S2 = 1;
l.push_back(s2);
l.push_back(s1);
list<S>::iterator it = find_if(l.begin(), l.end(), [] (S s) { return s.S1 == 0; } );
}
Code works fine on VS2012, just one recommendation, pass object by reference instead of pass by value:
list<S>::iterator it = find_if(l.begin(), l.end(), [] (const S& s) { return s.S1 == 0; } );

using a nested vector in C++

I am trying to implement a vector<int> within a vector<Type> in C++. However whenever I run the following code, I get an error reading
std::vector<std::vector<int> >::const_iterator’ has no member named ‘begin’
std::vector<std::vector<int> >::const_iterator’ has no member named ‘end’
Here is the code:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
typedef vector<int> vector1D ;
typedef vector<vector1D > vector2D ;
void showarr(const vector2D& v)
{
for (vector<vector1D >::const_iterator it1 = v.begin(); it1 != v.end(); ++it1) {
for(vector<int>::const_iterator it2 = *it1.begin(); it2 != *it1.end(); ++it2) {
cout<<*it2<<endl;
}
}
}
int main(int argc, char *argv[])
{
int rownum;
cin>>rownum;
vector2D a;
for ( int i = 0 ; i < rownum ; i++) {
a.push_back(vector1D(rownum,0));
}
showarr(a);
return 0;
}
Any type of help is appreciated.
Try changing:
*it1.begin()
to
it1->begin()
It's being parsed as *(it1.begin()), not (*it1).begin(). Change it to it1->begin().
The problem is in the line containing *itr.begin(). Change it to itr->begin(). This way, you won't get any errors.