繁体   English   中英

向量值(字符串和整数)求和 C++

[英]Vector Values (String and Int) Summation C++

我已经从 Python 移到 C++,只是想知道如何对向量(列表)object 持有的值求和。 例如,在 python 中,我可以使用以下代码:

totalSum = 0
myList = [1,2,3,4,5]

for i in myList:
    totalSum += i

print(totalSum)
// Output:
15

但是,我想学习在 C++ 中执行此操作的方法

totalSum = ""
myList = ["Hello", "World!"]

for i in myList:
    totalSum += i
    totalSum += " "

print(totalSum)
//Output:
Hello World!

而这个是用于字符串组合的。

您能否提供如何在 c++ 中执行此操作?

我已经在 C++ 中尝试了下面的代码来测试,但是,它没有编译成功:

#include <iostream>
#include <vector>
using namespace std;


int main()
{
    
    // A random list/vector here:
    vector <double> v = {1, 2, 3, 4, 5};

    // Declaring the final string to gather all the vector values:
    int sum;

    // Iterating through the vector
    for (int i = 0; i < v.size(); i++) {
        sum += v[i];
    }
    
    cout << sum;

    return 0;
}

除了您没有初始化 sum 变量之外,您的代码工作正常。

这是一些不言自明的代码,讨论您可以使用的内容(基于您对问题的评论):

#include <iostream>
#include <numeric>
#include <string>
#include <vector>

int main() {

    // For strings:

    std::string str;
    std::vector<std::string> v = {"Hello", "World!"};

    // Method 1: Using range-based for loop:
    for (auto &&i : v) {
        str += i;
        str += " ";
    }
    std::cout << str << std::endl;

    // Method 2: Using std::accumulate():
    str = std::accumulate(v.begin(), v.end(), std::string(), [](std::string a, std::string b) {
        return std::move(a) + b + " ";
    });
    std::cout << str << std::endl;

    // Method 3: The usual for-loop:
    str = "";
    for (size_t i = 0; i < v.size(); ++i) {
        str += v.at(i); // str += v[i];
        str += " ";
    }
    std::cout << str << std::endl;

    // Method 4: Using iterators:
    str = "";
    for (auto i = v.begin(); i < v.end(); ++i) { // for (auto i = std::begin(v); i < std::end(v); std::advance(i))
        str += *i;
        str += " ";
    }
    std::cout << str << std::endl;

    // For numbers:

    std::vector<int> v2  = {1, 2, 3, 4, 5};
    int sum = 0;

    // Method 1: Using range-based for loop:
    for (auto &&i : v2)
        sum += i;
    std::cout << sum << std::endl;

    // Method 2: Using std::accumulate():
    sum = std::accumulate(v2.begin(), v2.end(), 0);
    std::cout << sum << std::endl;

    // Method 3: The usual for-loop:
    sum = 0;
    for (size_t i = 0; i < v2.size(); ++i)
        sum += v2.at(i); // sum += v2[i]
    std::cout << sum << std::endl;

    // Method 4: Using iterators:
    sum = 0;
    for (auto i = v2.begin(); i < v2.end(); ++i) // for (auto i = std::begin(v2); i < std::end(v2); std::advance(i))
        sum += *i;
    std::cout << sum << std::endl;

    return 0;
}

如果您使用 C++14 或更高版本,则可以将传递给std::accumulate的 lamda 的参数列表从(std::string a, std::string b)替换为(auto a, auto b)

如果您使用std::begin()std::end()std::advance() ,则需要包含<iterator> 如果您不使用std::accumulate() ,您也可以删除<numeric>

有关您在我的代码中看到的任何不熟悉内容的文档,请访问https://en.cppreference.com/

程序有错误。 for循环中,您尝试将 integer 与v.size()返回的unsigned long long int进行比较(在编译器 arguments 中使用-Wall模式来获取它)。

使用每种语法,方法定义如下:

#include <iostream>
#include <vector>

int main(void) {
    std::vector <std::string> v = {"Hello", "World"};
    std::string sum;

    for (auto i : v) {
        sum += i;
        sum += ' ';
    }
    
    std::cout << sum << std::endl;

    return 0;
}

这将打印:

Hello World

如果您对 STL 算法感兴趣,可以使用std::accumulate来实现:

#include <vector>
#include <numeric>
#include <string>
#include <iostream>

int main()
{
    std::vector <double> v = {1, 2, 3, 4, 5};
    std::cout << std::accumulate(v.begin(), v.end(), 0.0) << "\n"; 

    std::vector<std::string> s = {"Hello", "World", "abc", "123"};
    std::cout << std::accumulate(s.begin(), s.end(), std::string(), 
                                [](auto& total, auto& str) { return total + str + " "; });  
}

Output:

15
Hello World abc 123 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM