Could we add elements in a vector<int> n; with cin >> n[i]; in a loop in C++?
Just interested in knowing and it's my first experience using stack overflow.
Could we add elements in a vector<int> n; with cin >> n[i]; in a loop in C++?
Just interested in knowing and it's my first experience using stack overflow.
If you don't know in advance how many items will end up in the vector you need to resize it as you read data. That's a job for a back inserter:
std::vector<int> n;
auto target = std::back_inserter(n);
while (std::cin >> *target++)
;
Because target is a back inserter, storing a value into *target appends the value to the vector with push_back, so each element gets properly inserted at the end of the vector. The ++ doesn't actually do anything in this case, because push_back always appends, but it's there so that the code looks like any normal use of an output iterator. If you knew the size in advance you'd skip the push_back, and you'd need the ++:
std::vector<int> n(10);
auto target = n.begin();
while (target != n.end())
std::cin >> *target++;
Note that the two input statements are identical. That's what iterators are all about.
int will make the while loop stopstd::ifstream rather than the console, or by redirecting the console input to come from a file), trying to read past the end of the file will fail and terminate the input.std::cin >> n[i] in a loop. There are lots of ways to read data into a vector, but these two examples are the closest to what was asked.No. You cannot insert an element into a vector like that. n[i] can only access an element that is already present in the vector. It returns a reference to the i-th element. If there is one, you can use std::cin to assign it a value:
std::vector<int> n;
n.resize(24);
std::cin >> n[4];
This can also be used in a loop:
std::vector<int> n;
n.resize(24);
for (size_t i=0; i<n.size(); ++i) {
std::cin >> n[i];
}
However, you shouldn't write the loop like this, but use a range based for loop instead. It is less error prone:
for (auto& elem : n) {
std::cin >> elem;
}
You can also insert elements one by one via push_back or insert. However, if possible you should prefer one resize over many insertions (at least for int, for class types the situation is different).
cin >> n[i]will do it.std::size_t size; std::cin >> size; std::vector<int> values(size); for(int& value : values) { std::cin >> value; },