C++/Vector/vector
Содержание
- 1 Add class to a vector and then delete them one by one
- 2 Assign Items in int array to vector
- 3 Assign value to the last Item
- 4 Computing an inner product of tuples represented as vectors
- 5 Demonstrating STL vector constructors with a user-defined type
- 6 Demonstrating STL vector constructors with a user-defined type and showing copying explicitly
- 7 Demonstrating STL vector copying constructors
- 8 Demonstrating the simplest STL vector constructors: duplicate chars
- 9 Demonstrating the simplest STL vector constructors: empty vector
- 10 Pass vector of integer to a function
- 11 Pass vector to a function
- 12 Read keyboard input to a vector
- 13 Requirements for Classes Used in Vectors
- 14 Store a class object in a vector
- 15 Use generic vector to create vector of chars
- 16 Use generic vector to create vector of integers
- 17 Use generic vector to create vector of strings
- 18 Use typedef to define new type based on vector
Add class to a vector and then delete them one by one
<source lang="cpp">
- include <iostream>
- include <vector>
using namespace std; class MyClass { }; int main( ) {
vector<MyClass*> vec; MyClass* p = NULL; for (int i = 0; i < 10; i++) { p = new MyClass( ); vec.push_back(p); } for (vector<MyClass*>::iterator pObj = vec.begin( ); pObj != vec.end( ); ++pObj) { delete *pObj; } vec.clear( );
}
</source>
Assign Items in int array to vector
<source lang="cpp">
- include <iostream>
- include <vector>
- include <cassert>
- include <numeric> // for accumulate
using namespace std; int main() {
int x[5] = {2, 3, 5, 7, 11}; vector<int> vector1(&x[0], &x[5]); int sum = accumulate(vector1.begin(), vector1.end(), 0); cout << sum << endl; return 0;
} /* 28
*/ </source>
Assign value to the last Item
<source lang="cpp">
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */
- include <iostream>
- include <vector>
- include <string>
- include <algorithm>
- include <iterator>
using namespace std; int main() {
// create empty vector for strings vector<string> sentence; // reserve memory for five Items to avoid reallocation sentence.reserve(5); // append some Items sentence.push_back("Hello,"); sentence.push_back("how"); sentence.push_back("are"); sentence.push_back("you"); sentence.push_back("?"); // assign "!" to the last Item sentence.back() = "!"; // print Items separated with spaces copy (sentence.begin(), sentence.end(), ostream_iterator<string>(cout," ")); cout << endl;
} /* Hello, how are you !
*/ </source>
Computing an inner product of tuples represented as vectors
<source lang="cpp">
- include <vector>
- include <iostream>
using namespace std; int main() {
const long N = 600000; // Length of tuples x and y const long S = 10; // Sparseness factor vector<double> x(N), y(N);
for (long k = 0; 3 * k * S < N; ++k) x[3 * k * S] = 1.0; for (long k = 0; 5 * k * S < N; ++k) y[5 * k * S] = 1.0; double sum = 0.0; for (long k = 0; k < N; ++k) sum += x[k] * y[k]; cout << sum << endl; return 0;
} /* 4000
*/ </source>
Demonstrating STL vector constructors with a user-defined type
<source lang="cpp">
- include <iostream>
- include <cassert>
- include <vector>
using namespace std; class MyClass { public:
unsigned long id; MyClass() : id(0) { } MyClass(unsigned long x) : id(x) { }
}; bool operator==(const MyClass& x, const MyClass& y) {
return x.id == y.id;
} bool operator!=(const MyClass& x, const MyClass& y) {
return x.id != y.id;
}
int main() {
vector<MyClass> vector1, vector2(3); assert (vector1.size() == 0); assert (vector2.size() == 3); assert (vector2[0] == MyClass() && vector2[1] == MyClass() &&vector2[2] == MyClass()); assert (vector2 == vector<MyClass>(3, MyClass())); return 0;
}
</source>
Demonstrating STL vector constructors with a user-defined type and showing copying explicitly
<source lang="cpp">
- include <iostream>
- include <cassert>
- include <vector>
using namespace std; class MyClass { public:
unsigned long id; unsigned long generation; static unsigned long total_copies; MyClass() : id(0), generation(0) { } MyClass(unsigned long n) : id(n), generation(0) { } MyClass(const MyClass& z) : id(z.id), generation(z.generation + 1) { ++total_copies; }
}; bool operator==(const MyClass& x, const MyClass& y) {
return x.id == y.id;
} bool operator!=(const MyClass& x, const MyClass& y) {
return x.id != y.id;
} unsigned long MyClass::total_copies = 0; int main() {
vector<MyClass> vector1, vector2(3); assert (vector1.size() == 0); assert (vector2.size() == 3); assert (vector2[0] == MyClass() && vector2[1] == MyClass() && vector2[2] == MyClass()); for (int i = 0; i != 3; ++i) cout << "vector2[" << i << "].generation: " << vector2[i].generation << endl; cout << "Total copies: " << MyClass::total_copies << endl; return 0;
} /* vector2[0].generation: 1 vector2[1].generation: 1 vector2[2].generation: 1 Total copies: 3
*/ </source>
Demonstrating STL vector copying constructors
<source lang="cpp">
- include <iostream>
- include <cassert>
- include <vector>
using namespace std; int main() {
char name[] = "abcedfghijklmn"; vector<char> myVector(name, name + 6); vector<char> myVector2(myVector); // Uses copy constructor assert (myVector2 == myVector); return 0;
}
</source>
Demonstrating the simplest STL vector constructors: duplicate chars
<source lang="cpp">
- include <iostream>
- include <cassert>
- include <vector>
using namespace std; int main() {
vector<char> vector2(3, "x"); assert (vector2.size() == 3); assert (vector2[0] == "x" && vector2[1] == "x" && vector2[2] == "x"); assert (vector2 == vector<char>(3, "x")); return 0;
}
</source>
Demonstrating the simplest STL vector constructors: empty vector
<source lang="cpp">
- include <iostream>
- include <cassert>
- include <vector>
using namespace std; int main() {
vector<char> vector1; cout << vector1.size(); return 0;
} /* 0
*/ </source>
Pass vector of integer to a function
<source lang="cpp">
- include <iostream>
- include <numeric>
- include <vector>
- include <cmath>
- include <functional>
using namespace std; double geometricMean(const vector<int>& nums) {
double mult = accumulate(nums.begin(), nums.end(), 1,multiplies<int>()); return (pow(mult, 1.0 / nums.size()));
}
int main(int argc, char** argv) {
plus<int> myPlus; int res = myPlus(4, 5); cout << res << endl; vector<int> myVector; int num; while (true) { cout << "Enter a test score to add (0 to stop): "; cin >> num; if (num == 0) { break; } myVector.push_back(num); } cout << "The geometric mean is " << geometricMean(myVector) << endl; return (0);
}
</source>
Pass vector to a function
<source lang="cpp">
- include <iostream>
using std::cout; using std::endl;
- include <vector>
using std::vector; template < typename T > void printVector( const vector< T > &integers2 ); int main() {
int array[ 6 ] = { 1, 2, 3, 4, 5, 6 }; // initialize array vector< int > integers; // create vector of ints integers.push_back( 2 ); integers.push_back( 3 ); integers.push_back( 4 ); printVector( integers ); cout << endl; return 0;
} template < typename T > void printVector( const vector< T > &integers2 ){
typename vector< T >::const_iterator constIterator; for ( constIterator = integers2.begin(); constIterator != integers2.end(); ++constIterator ) cout << *constIterator << " ";
} /* 2 3 4
*/ </source>
Read keyboard input to a vector
<source lang="cpp">
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */
- include <iostream>
- include <string>
- include <algorithm>
- include <iterator>
- include <vector>
using namespace std; int main() {
/* create a string vector * - initialized by all words from standard input */ vector<string> coll((istream_iterator<string>(cin)), istream_iterator<string>()); // sort Items sort (coll.begin(), coll.end()); // print all Items ignoring subsequent duplicates unique_copy (coll.begin(), coll.end(), ostream_iterator<string>(cout, "\n"));
} /* Terminate batch job (Y/N)? n
*/ </source>
Requirements for Classes Used in Vectors
<source lang="cpp">
- include <iostream>
- include <vector>
using namespace std; template <class T> void print(T& c){
for( typename T::iterator i = c.begin(); i != c.end(); i++ ){ std::cout << *i << endl; }
} class Item {
public: Item(); ~Item(); Item( const Item& ); Item& operator=( const Item& ); private: static int default_constructor_calls_; static int assignment_calls_; static int copy_constructor_calls_; static int destructor_calls_;
}; inline Item::Item() { cout << "\nCall " << ++default_constructor_calls_
<< " of default constructor";
} inline Item::Item( const Item& ) {
cout << "\nCall " << ++copy_constructor_calls_ << " of copy constructor";
} inline Item::~Item() { cout << "\nCall " << ++destructor_calls_ << " of destructor"; } inline Item& Item::operator=( const Item& ) {
cout << "\nCall " << ++assignment_calls_ << " of assignment operator"; return *this;
} int Item::default_constructor_calls_ = 0; int Item::assignment_calls_ = 0; int Item::copy_constructor_calls_ = 0; int Item::destructor_calls_ = 0; int main( ) {
vector<Item> d( 2 ); d.resize( d.capacity() ); d.push_back( Item() ); d.erase( d.begin() );
}
</source>
Store a class object in a vector
<source lang="cpp">
- include <iostream>
- include <vector>
- include <cstdlib>
using namespace std; class MyClass {
int value;
public:
MyClass() { value = 0; } MyClass(int x) { value = x; } MyClass &operator=(int x) { value = x; return *this; } double get_value() { return value; }
}; bool operator<(MyClass a, MyClass b) {
return a.get_value() < b.get_value();
} bool operator==(MyClass a, MyClass b) {
return a.get_value() == b.get_value();
} int main() {
vector<MyClass> v; for(int i=0; i<7; i++) v.push_back(MyClass(60 + rand()0)); cout << "Farenheit valueeratures:\n"; for(int i=0; i<v.size(); i++) cout << v[i].get_value() << " "; cout << endl; for(int i=0; i<v.size(); i++) v[i] = (int) (v[i].get_value()-32) * 5/9 ; cout << "Centigrade valueeratures:\n"; for(int i=0; i<v.size(); i++) cout << v[i].get_value() << " "; return 0;
} /* Farenheit valueeratures: 71 77 64 70 89 64 78 Centigrade valueeratures: 21 25 17 21 31 17 25
*/ </source>
Use generic vector to create vector of chars
<source lang="cpp">
- include <iostream>
- include <cassert>
- include <vector>
- include <algorithm> // For find
using namespace std;
int main() {
char x[5] = {"a", "b", "c", "d", "f"}; vector<char> vector1(&x[0], &x[5]); // Search for the first occurrence vector<char>::iterator where = find(vector1.begin(), vector1.end(), "b");
cout << *where << endl; return 0;
} /* b
*/ </source>
Use generic vector to create vector of integers
<source lang="cpp">
- include <iostream>
- include <cassert>
- include <vector>
- include <algorithm> // For find
using namespace std;
int main() {
int x[5] = {2, 4, 6, 8, 10}; vector<int> vector1(&x[0], &x[5]); // Search for the first occurrence vector<int>::iterator where = find(vector1.begin(), vector1.end(), 4);
cout << *where << endl; return 0;
} /* 4
*/ </source>
Use generic vector to create vector of strings
<source lang="cpp">
// Demonstrating the generic find algorithm with a vector
- include <iostream>
- include <cassert>
- include <vector>
- include <algorithm> // For find
using namespace std;
int main() {
string x[5] = {"1234", "2345", "3456", "4567", "0987"}; vector<string> vector1(&x[0], &x[5]); // Search for the first occurrence vector<string>::iterator where = find(vector1.begin(), vector1.end(), "1234");
cout << *where << endl; return 0;
} /* 1234
*/ </source>
Use typedef to define new type based on vector
<source lang="cpp">
- include <algorithm>
- include <vector>
- include <string>
- include <iostream>
using namespace std; typedef vector <string> VECTOR_STRINGS; int main () {
VECTOR_STRINGS v; v.push_back ("A"); v.push_back ("B"); v.push_back ("C"); v.push_back ("D"); // insert a duplicate into the vector v.push_back ("D"); for (size_t nItem = 0; nItem < v.size (); ++ nItem){ cout << "Name [" << nItem << "] = \""; cout << v [nItem] << "\"" << endl; } return 0;
}
</source>