Getting error while inputting value at 2d vector - c++

I am using Codeblock to write c++ code. I was trying to input value at 2d vector. But it is getting an error. I am new at c++ and I have already searched at google but haven't found any solution. This is my code
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <vector<double>> customar_data;
double value;
cin >> value;
customar_data[0][0].push_back(value);
cout >> customar_data[0][0];
return 0;
}
This is what codeblocks compiler showing

For the compiler's error, look at the types of the expressions involved.
customar_data is a vector <vector <double>>
customar_data[0] is a <vector <double>>
customar_data[0][0] is a double
The compiler complains when you request a member function (push_back) of the non-class type double.
For the logical error, look at what you are requesting. You start by constructing an empty vector (of vector<double>). Then you try to access the first element of this empty vector. You can avoid the need to specify the vector's size during construction, or you can access elements without adding them to the constructed vector, but you cannot do both. Vectors do not automatically increase in size as a result of accessing elements that had not existed.
The valid indices/subscripts to access are the non-negative integers less than the vector's size(). A default constructed vector starts with a size of zero, so there are no valid indices (you would need a non-negative integer less than zero). If you know how big you want the outermost vector to be when you construct it, you may want to specify that.
vector <vector<double>> customar_data(10);
// At this point, customar_data[0] through customar_data[9] can be used.
// Each of these elements is an empty vector of doubles.
If you do not know how big the outermost vector is going to be, you'll need to add each element before you use it. (This is intentionally singular; you can add an element, use it, then add another.)
vector <vector<double>> customar_data;
customar_data.push_back(vector<double>()); // Adds an empty vector as the first element.
customar_data[0].push_back(20.0); // Adds a value to the vector that is the first element.
// At this point, customar_data[0][0] is valid and has the value 20.0.
You might find that the emplace_back member function is more convenient than push_back, but let's go one step at a time.

Related

how to push_back vector with no size in a specific location?

I'm trying to get a solid understanding of Vectors. So i understand if we init vectors as following we specify the exact location in array for the vector to exist
vector<int> temp[5];
temp[i].push_back(randomInt);(i a random position)
but what if i'm trying to have a vector without specified size because i do not know the amount of input? how would i define the first index for example of temp as i did previously using the following init?
vector<int> temp;
here:
vector<int> temp[5];
you declared an array of 5 vectors, but going by your description it looks like you're meant to declare one vector with pre-allocated 5 elements (if so, then it should have been like vector<int> temp(5);)
how would i define the first index for example of temp as i did
previously using the following init?
all the std containers have methods allowing you to push / emplace data (i.e. to extend them) and method size() allowing to check the current size of the container.

How are vectors(in C++) having elements of variable size allocated?

I wrote the following code to accept test-cases on a competetive programming website. It uses a vector input of the structure case to store the inputs for given test-cases all at once, and then process them one at a time( I have left out the loops that take the input and calculate the output because they are irrelevant to the question.)
#include<iostream>
#include<vector>
using namespace std;
struct case{
int n, m;
vector<int> jobsDone;
};
int main(){
int testCase;
cin>>testCase;
vector<case> input;
input.reserve(testCase);
//The rest of the code is supposed to be here
return 0;
}
As I was writing this code, I realised that the working of input.reserve(t) in such a case where the element size is variable(since each instance of the structure case also has a vector of variable size) would be difficult. Infact, even if I had not explicitly written the reserve() statement, the vector still would have reserved a minumum number of elemtns.
For this particular situation, I have the following questions regarding the vector input:
Wouldn't random access in O(1) time be impossible in this case, since the beginning position of every element is not known?
How would the vector input manage element access at all when the beginning location of every element cannot be calculated? Will it pad all the entries to the size of the maximum entry?
Should I rather be implementing cases using a vector of pointers pointing to each instance of case? I am thinking about this because if the vector pads each element to a size and wastes space, or it maintains the location to each element, and random access is not constant in time, hence there is no use for a vector anyway.
Every object type has a fixed size. This is what sizeof returns. A vector itself typically holds a pointer to the array of objects, the number of objects for which space has been allocated, and the number of objects actually contained. The size of these three things is independent of the number of elements in the vector.
For example, a vector<int> might contain:
1) An int * holding the address of the data.
2) A size_t holding the number of objects we've allocated space for
3) A size_t holding the number of objects contained in the vector.
This will probably be somewhere around 24 bytes, regardless of how many objects are in the vector. And this is what sizeof(vector<int>) will return.

Implementation defined to use a reserved vector without resizing it?

Is it implementation defined to use a reserved vector without resizing it?
By that I mean:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<unsigned int> foo;
foo.reserve(1024);
foo[0] = 10;
std::cout<<foo[0];
return 0;
}
In the above, I reserve a good amount of space and I assigned a value to one of the indices in that space. However, I did not call push_back which "resizes" the vector and gives it a default value for each element (which I'm trying to avoid). So in this foo.size() is 0 while foo.capacity() is 1024.
So is this valid code or is it implementation defined? Seeing as I'm assigning to a vector with "0" size. It works but I'm not sure if it's a good idea..
The reason I'm trying to avoid the default value is because for large allocations, I don't need it "zero-ing" out each index as I will decide when I want to write to it or not. I'd use a raw pointer but the lodepng API accepts only a vector for decoding from file.
std::vector::reserve just reserves memory, so the next push_back does not have to allocate memory. It does not change the size of the vector.
If you want a vector with an initial size of 1024 elements, you can use the constructor to do that:
std::vector<unsigned int> foo(1024);
Note that if you create a vector with an initial size of e.g. 1024 elements, if you then do push_back you add an element, so the size of the vector increases to 1025 elements.
It is illegal, regardless of the type of item in the container or what seems to happen on a particular compiler. From 23.1.1/12 (Table 68) we learn that operator[] behaves like *(a.begin() + n). Since you haven't added any items to the container this is the same as accessing an iterator past end() which is undefined.

how to store vector of vector by index

Hi I have to store the below mentioned information in a vector of vectors format...
vector <vector <int>> ph;
vector<int> p, q;
p.push_back(1);
p.push_back(2);
p.push_back(3);
q.push_back(10);
q.push_back(20);
q.push_back(30);
q.push_back(40);
Now instead of using:
ph.push_back(p);
ph.push_back(q);
I want to use:
ph.at(0)=p
ph.at(1)=q
(This is the error that I am getting when I am using this: terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check)
The reason why I want to store it this way is....later I want to access the elements of a particular vector identified by its index i.e. 1 or 0.
For example I wish to access ph[0].size() i.e the size of p...identified by its index. That is, I want to perform the same operation as we are able to do in the case of simple arrays in c++ i.e. store the data in that array at a particular index and access the data from a particular index.
You are getting the error because when you instantiate the vector of vectors, it has size 0, and the at() method is allowed to do bound checks and raise an exception.
If you want to access by index like that then you are better off with an std::map or std::unordered_map. That makes the index independent of the order of insertion:
std::map<int, std::vector<int>> MapOfVectors;
std::vector<int> p, q;
// fill vectors
MapOfVectors[1] = q;
MapOfVectors[0] = p;
Otherwise, you would have to make sure your vector of vectors is large enough to insert elements by index:
// instantiate vector with size 2. You can insert p and q by index. (0, 1) only
vector<vector<int>> ph(2);
Or, resize it after creation:
vector<vector<int>> ph;
ph.resize(2);
When you define vector<vector<int>> ph the vector ph is empty. The .at() member function does bounds checking and correctly throws an exception when you try to write to non-existing elements.
You could do ph.resize(2) so that indices 0-1 would then be valid or just use push_back like you do currently.
I want to use:
ph.at(0)=p ph.at(1)=q
That attempts to access indices past the end of the array, hence the exception.
The reason why I want to store it this way is....later I want to access the elements of a particular vector identified by its index i.e. 1 or 0.
For example I wish to access ph[0].size() i.e the size of p...identified by its index. That is, I want to perform the same operation as we are able to do in the case of simple arrays in c++ i.e. store the data in that array at a particular index and access the data from a particular index.
You can achieve this by first filling the outer vector with empty inner vectors:
vector<vector<int> > ph(2);
Here, the 2 says to construct the outer vector to contain 2 default-constructed elements (themselves vector<int>).
Alternatively, you can use:
vector<vector<int> > ph;
ph.resize(2);
After you've done that, it will be safe to access the elements to store non-default-constructed values. That means the following won't throw:
ph.at(0)=p; ph.at(1)=q;

Stumped at a simple segmentation fault. C++

Could somebody be kind to explain why in the world this gives me a segmentation fault error?
#include <vector>
#include <iostream>
using namespace std;
vector <double>freqnote;
int main(){
freqnote[0] = 16.35;
cout << freqnote[0];
return 0;
}
I had other vectors in the code and this is the only vector that seems to be giving me trouble.
I changed it to vector<int>freqnote; and changed the value to 16 and I STILL get the segmentation fault. What is going on?
I have other vector ints and they give me correct results.
Replace
freqnote[0] = 16.35;
with
freqnote.push_back(16.35);
and you'll be fine.
The error is due to that index being out-of-range. At the time of your accessing the first element via [0], the vector likely has a capacity of 0. push_back(), on the other hand, will expand the vector's capacity (if necessary).
You can't initialise an element in a vector like that.
You have to go:
freqnote.push_back(16.35),
then access it as you would an array
You're accessing vector out of bounds. First you need to initialize vector specifying it's size.
int main() {
vector<int> v(10);
v[0] = 10;
}
As has been said, it's an issue about inserting an out of range index in the vector.
A vector is a dynamically sized array, it begins with a size of 0 and you can then extend/shrink it at your heart content.
There are 2 ways of accessing a vector element by index:
vector::operator[](size_t) (Experts only)
vector::at(size_t)
(I dispensed with the const overloads)
Both have the same semantics, however the second is "secured" in the sense that it will perform bounds checking and throw a std::out_of_range exception in case you're off bound.
I would warmly recommend performing ALL accesses using at.
The performance penalty can be shrugged off for most use cases. The operator[] should only be used by experts, after they have profiled the code and this spot proved to be a bottleneck.
Now, for inserting new elements in the vector you have several alternatives:
push_back will append an element
insert will insert the element in front of the element pointed to by the iterator
Depending on the semantics you wish for, both are to be considered. And of course, both will make the vector grow appropriately.
Finally, you can also define the size explicitly:
vector(size_t n, T const& t = T()) is an overload of the constructor which lets you specify the size
resize(size_t n, T const& t = T()) allows you to resize the vector, appending new elements if it gets bigger than it was
Both method allow you to supply an element to be copied (exemplar) and default to copying a default constructed object (0 if T is an int) if you don't supply the exemplar explicitly.
Besides using push_back() to store new elements, you can also call resize() once before you start using the vector to specify the number of elements it contains. This is very similar to allocating an array.