Why it says 'push_back' has not been declared? - c++

Why it says 'push_back' has not been declared ?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> v(30);
v[0].push_back(0);
return 0;
}

v[0] is a reference to the initial element in the vector; it isn't the vector itself. The element is of type int, which is not a class type object and therefore has no member functions.
Are you looking for v.push_back(0);?
Note that vector<int> v(30); creates the vector with 30 elements in it, each with a value of zero. Calling v.push_back(0); will increase the size of the vector to 31. This may or may not be the behavior your want; if it isn't, you'll need to clarify what, exactly, you are trying to do.

You need to do v.push_back(0) as push_back is the method of the vector not its element.

Try this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> v(30);
v.push_back(0);
return 0;
}
The problem is that v[0] is the first element in vector, which is an int. The name of the vector is v.

Just use v.push_back(0); You have to push_back into a vector. Not into a specific element of a vector.

You have the wrong type.
v is of type Vector. v[0] is NOT a vector, rather, it is a reference to the first element (which will be an int).
As a result, v[0] does not have a push_back method.
Only the vector itself (v) has the method.

use v.push_back(0) as v[0] is an int and not a vector.

Related

Get pointer to 1st element of std::list

Here I have simple code, it works for std::vector, but don't work for std::list.
Is it wrong because elements in list doesn't alighned?
Edit:
Ok, what is the best way to put list in func? Convert it to vector?
for example I need it when put data in PolyPolyLine
#include <iostream>
#include <vector>
#include <list>
using namespace std;
vector<int> func(int* buf)
{
vector<int> t;
t.push_back(buf[0]);
t.push_back(buf[1]);
return t;
}
int main() {
list<int> ls;
vector<int> v;
ls.push_back(2);
ls.push_back(111111);
v.push_back(12);
v.push_back(11);
vector<int> t1= func(&v[0]);
vector<int> t2= func(&ls.front());
cout<<t1[0]<<t1[1];
cout<<t2[0]<<t2[1];
return 0;
}
The std::list<T> is a linked list, so its memory is not contiguous. You cannot use regular pointers with it to do pointer arithmetic - it's undefined behavior.
If you change your program to take iterators instead, and use std::next to access elements beyond the current one, your program would produce the behavior that you expect.
template <typename T>
vector<int> func(T buf)
{
vector<int> t;
t.push_back(*next(buf, 0));
t.push_back(*next(buf, 1));
return t;
}
...
vector<int> t1= func(v.begin());
vector<int> t2= func(ls.begin());
Demo.
You can't take the address of an item in a list and use it as an array. std::list is a doubly linked list with dynamically allocated nodes. Unlike a vector, the elements in the list are not contiguous.
The only container that guarantees continuous memory allocation is std::vector (and std::array). You don't have any sort of guarantee like that with a std::list, which is why this approach can't possibly work.

Segmentation fault while initializing vector by an initialized array in C++

I wanted to use the sort() in the algorithm library in C++. I could find examples for sorting vectors only, thus I am trying to initialize a vector by an initialized array. When executing I am getting a segmentation fault and couldn't figure out what is wrong here in the code I wrote.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n,k,packet[1000],min=0;
scanf("%d",&n);
scanf("%d",&k);
for (int i = 0; i < n; ++i)
{
scanf("%d",&packet[i]);
cout<<i<<endl;
}
cout<<"debug";
vector<int> packets(packet,packet+n);
vector<int>::iterator start,stop;
sort(packets.begin(),packets.begin()+n);
min=*(packets.begin())- *(packets.end());
cout<<min;
for (vector<int>::iterator it=packets.begin(); it!=packets.end()-k; ++it)
{
printf("%d ",*it );
if((*(it+k) - *it)<min)
{
start=it;
stop=it+k;
}
}
printf("%d\n",*stop- *start );
return 0;
}
*(packets.end())
packets.end() returns an iterator to the element, following the last element of the vector.
Attempting to derefenrence it causes Undefined Behavior.
The comments explain that you can use sort with an array just fine (if you look at http://en.cppreference.com/w/cpp/algorithm/sort you'll see that sort takes two arguments that: -RandomIt must meet the requirements of ValueSwappable and RandomAccessIterator.. Plain pointers fulfill this requirement).
In your example, the segfault happens because you try to dereference a valid but undereferencable iterator (the iterator returned by 'end()' in: min=*(packets.begin())- *(packets.end());. Basically it returns an iterator that points to after the last element of the vector. If you want to get an iterator to the last element, you can use rbegin() but of course you need to make sure that the vector is not empty first).
You could have seen this quite easily by running your code under a debugger, you'd see that the segmentation fault had nothing to do with the call to sort

how to check a value exists in a c++ stl vector and apply a function to every element of the vector?

I have two questions related to the vector class of the standard library in C++.
How can I check whether a value (let's say of an integer) already exists in a vector?
What I want in words is as follows: "if the integer already exists in the vector, next one, else add it at the end of the vector."
How do I apply a function that holds arguments to every element in the vector? (It seems I can't do that with for_each)
In words: "for each z element in the vector apply MyAddFn(i,j)"
... or maybe I'm not on the right track with the stl vector sequence container, and I should define my own iterator?
1)
std::find(v.begin(), v.end(), 5) == v.end() // checks that vector<int> v has no value 5.
2) Use new C++11 std::bind for example, but for real advice i need more context of use MyAddFn.
For 1, use std::find algorithm. If the element does not exist, it returns the iterator to the end. In that case, add the element.
2nd question. You can use object instead of function:
#include <vector>
#include <algorithm>
class apply_me
{
int multiplicator_;
public:
apply_me(const int multiplicator) : multiplicator_(multiplicator)
{};
int operator ()(const int element) const
{
return element*multiplicator_;
};
};
int main()
{
std::vector<int> v;
std::transform(v.begin(), v.end(),v.begin(), apply_me(3));
}

Insert vector for value in map in C++

I am stuck on trying to figure out how to insert a vector for a value in a map. For example:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main()
{
map <int, vector<int> > mymap;
mymap.insert(pair<int, vector<int> > (10, #put something here#));
return 0;
}
I don't know what syntax to use insert a vector for value. I tried {1,2}, but that failed. What syntax should I use?
Everything works if I declare a vector in advance and give it a name, but I don't want to do that, as I want to have a map with a lot of vectors.
Thank You in Advance
If you want an empty vector you could do:
mymap.insert(pair<int,vector<int> >(10, vector<int>()));
You could then add whatever elements you want with something like:
mymap[10].push_back(1);
mymap[10].push_back(2);
Edit: Removed incorrect assertion that the vectors would be copied if/when the map grows. As the commenters pointed out, this is not true for std::map, which is node-based.
Basically your question is not about inserting std::vector into a std::map. Your question is how can you easily create an anonymous std::vector with arbitrary initial element values.
In ISO C++03, you can't. C++11 allows using initialization lists for this, however.
If you are stuck with a C++03 compiler, you possibly could create a helper function to return a vector with specified elements:
std::vector<int> make_vector(int a, int b)
{
std::vector<int> v;
v.push_back(a);
v.push_back(b);
return v;
}
If the vectors you're inserting are of different sizes, you could use a variadic function, although doing so would require that you either pass along the number of elements or have a reserved sentinel value.
If you are using C++11 you can use vector's initialization list constructor (the last constructor in that list) which would look like this:
mymap.insert(pair<int, vector<int> > (10, {1, 2, 3}));
If you can only use C++03, vector has a constructor that takes a size and a default value for each element that might be enough for you. Otherwise you will have to construct the vector and then insert it. If you want to avoid an unnessicary copy of the vector when inserting you could swap it in like so:
vector<int> myvec;
myvec.push_back(1);
myvec.push_back(2);
mymap[10].swap(myvec);
This way the vector won't need to be copied. You'll get an extra vector default construction but that's not very expensive.
#put something here# = vector<int>{1,2}
I'm surprised though that {1,2} didn't work. Are you not using a C++11 compiler? If not then you can only create the vector with default constructor there (no values), or fill it with values first and stick it in.
This should work in C++2003 compilers.
#include <iostream>
#include <vector>
#include <map>
#include <cassert>
using namespace std;
std::vector<int> make_vector(int a, int b) {
std::vector<int> result;
result.push_back(a);
result.push_back(b);
return result;
}
int main()
{
map <int, vector<int> > mymap;
mymap.insert(make_pair(10, make_vector(1,2)));
// Or, alternatively:
// mymap[10] = make_vector(1,2);
assert(mymap[10][0] == 1);
assert(mymap[10][1] == 2);
return 0;
}
C++03 does not have initializer lists, which can be a pain to initialize collections.
If you cannot upgrade to a more modern version of the compiler, you can always use the Boost.Assignment library. It has a list_of function precisely for this.
#put something here# -> boost::assign::list_of(1)(2)

How to use sort to sort a vector in a class

I was wondering how I can use the sort function to sort a vector which is private in a class:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class A{
private:
const vector<int> myvec;
A(vector<int>& vec) : myvec(vec) { }
public:
const vector<int>& getvec() { return myvec; }
int get_sec_element(){
int sec_ele = 0;
sort(myvec.begin(), myvec.end());
sec_ele = myvec[2];
return sec_ele;
}
};
So if I created A myvec_object and filled it with a vector which had values already inside it, caliing myvec_object.get_sec_ele() would return the 2nd element in the vector. However, the compiler is giving a huge error message with: "instantiated from here". What could be the problem?
You declared myvec as const -- how would you expect to modify it?
Declare myvec as:
vector<int> myvec;
You have defined your vector as const; this makes it immutable after initialization. If you intend to sort the vector, you'll need to un-const it, or make a copy to sort (which would be slow, of course, if you intend to do this more than once).
You've declared the member variable myvec as const, but std::sort has to modify the vector to sort it. You could:
Make the vector non const by removing the const keyword from its declaration
First make a copy of the vector and sort the copy
replace std::vector with std::multiset, which will keep the items in sorted order to begin with.