1、大致有以下幾種方法實現用於把一個vector賦值給另一個vector:
方法1:
1 |
vector<int > v1(v2);//聲明 |
方法2:使用swap進行賦值:
1 |
vector<int > v1();v1.swap(v2);//將v2賦值給v1,此時v2變成了v1 |
方法3:使用函數assign進行賦值:
1 2 |
vector<int > v1;//聲明v1 v1.assign(v2.begin(), v2.end());//將v2賦值給v1 |
方法4:使用循環語句賦值,效率較差
1 2 3 4 |
vector<int >::iterator it;//聲明迭代器 for(it = v2.begin();it!=v2.end();++it){//遍歷v2,賦值給v1 v1.push_back(it); }/
|
2、對非靜態成員引用必須與特定對象相對 這句話 是什麼意思!
意思就是引用非靜態成員前應該先聲明該類的對象。
比如類A這樣定義
class A
{
private:
int n;
}
要使用n就要先這樣聲明A的對象,或者是使用class中的一個非靜態成員函數,也必須這樣使用。
A a;
a.n=1
3.注意變量在哪個{}裏面定義,那麼這個變量的作用域就在那個括號裏面,在{}外面是不可見的。
4、記住對vector的輸出只能是逐個輸出,不能將整個vector進行輸出。
t題目:
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
#ifndef _Solution_
#define _Solution_
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
vector<string> fizzBuzz(intn) {
vector<string>fizzBuzz1;
for (unsigned int ix = 1;ix <= n; ++ix)
if ((ix % 3)&& (ix % 5)){
string s =to_string(ix);
fizzBuzz1.push_back(s);
s = "";
}
else if ((!(ix %3))&& (ix % 5))
fizzBuzz1.push_back("Fizz");
else if (!(ix %5)&& (ix % 3))
fizzBuzz1.push_back("Buzz");
else
fizzBuzz1.push_back("FizzBuzz");
return fizzBuzz1;
}
};
#endif
int main() {
static int n = 15;
Solution a;
vector<string>vectemp(a.fizzBuzz(n)); //在這裏定義一箇中間vector
//接受另外一個class裏面的vector
for (unsigned int ix = 0; ix <n;++ix) {
cout << vectemp[ix]<< endl;
}
}
5、記住operator<<的重載必須有一個是class的對象才能重載。
6、將int轉化成string,在c11裏面有函數to_string,可以進行轉化。