C++容器求和
时间: 2023-06-29 14:10:30 浏览: 135
C++求和程序
5星 · 资源好评率100%
可以使用STL中的容器来求和。以下是一些常用容器的示例:
1. vector:
```c++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers = {1, 2, 3, 4, 5};
int sum = 0;
for(int i = 0; i < numbers.size(); i++){
sum += numbers[i];
}
cout << "The sum is: " << sum << endl;
return 0;
}
```
2. list:
```c++
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> numbers = {1, 2, 3, 4, 5};
int sum = 0;
for(auto it = numbers.begin(); it != numbers.end(); it++){
sum += *it;
}
cout << "The sum is: " << sum << endl;
return 0;
}
```
3. set:
```c++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> numbers = {1, 2, 3, 4, 5};
int sum = 0;
for(auto it = numbers.begin(); it != numbers.end(); it++){
sum += *it;
}
cout << "The sum is: " << sum << endl;
return 0;
}
```
4. map:
```c++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int> numbers = {{"one", 1}, {"two", 2}, {"three", 3}, {"four", 4}, {"five", 5}};
int sum = 0;
for(auto it = numbers.begin(); it != numbers.end(); it++){
sum += it->second;
}
cout << "The sum is: " << sum << endl;
return 0;
}
```
以上示例中,我们使用了不同类型的容器来存储数值,并使用循环遍历容器中的元素进行求和。
阅读全文