A
arnuld
Exercise 4.28: Write a program to read the standard input and build a
vector of ints from values that are read. Allocate an array of the same
size as the vector and copy the elements from the vector into the
array.
here is the code i wrote. does anyone has a better idea?
#include <iostream>
#include <vector>
int main() {
const unsigned ivec_sz = 6;
std::vector<int> ivec(ivec_sz);
unsigned j;
// adding elements to vector
for(std::vector<int>::iterator iter = ivec.begin();
iter != ivec.end();
++iter)
{
std::cout << "Enter an integer: ";
std::cin >> j;
*iter = j;
}
// creating an array of same size as "ivec"
const unsigned arr_sz = ivec_sz;
int ia[arr_sz];
// reading from "vector" & writing into the "array"
int *pia = ia;
std::vector<int>::iterator iter_ivec=ivec.begin();
for(int *pbegin = ia, *pend = ia + arr_sz;
*pbegin != *pend;
++pbegin)
{
*pbegin = *iter_ivec;
++iter_ivec;
}
std::cout << "Printing array elements: " << std::endl;
for(int *pbegin = ia, *pend = ia + arr_sz;
*pbegin != *pend;
++pbegin)
{
std::cout << "array element: " << *pbegin << std::endl;
}
}
--arnuld
http://arnuld.blogspot.com
vector of ints from values that are read. Allocate an array of the same
size as the vector and copy the elements from the vector into the
array.
here is the code i wrote. does anyone has a better idea?
#include <iostream>
#include <vector>
int main() {
const unsigned ivec_sz = 6;
std::vector<int> ivec(ivec_sz);
unsigned j;
// adding elements to vector
for(std::vector<int>::iterator iter = ivec.begin();
iter != ivec.end();
++iter)
{
std::cout << "Enter an integer: ";
std::cin >> j;
*iter = j;
}
// creating an array of same size as "ivec"
const unsigned arr_sz = ivec_sz;
int ia[arr_sz];
// reading from "vector" & writing into the "array"
int *pia = ia;
std::vector<int>::iterator iter_ivec=ivec.begin();
for(int *pbegin = ia, *pend = ia + arr_sz;
*pbegin != *pend;
++pbegin)
{
*pbegin = *iter_ivec;
++iter_ivec;
}
std::cout << "Printing array elements: " << std::endl;
for(int *pbegin = ia, *pend = ia + arr_sz;
*pbegin != *pend;
++pbegin)
{
std::cout << "array element: " << *pbegin << std::endl;
}
}
--arnuld
http://arnuld.blogspot.com