我如何将此代码转换为C++?
string[] strarr = {"ram","mohan","sita"};
foreach(string str in strarr) {
listbox.items.add(str);
}
Run Code Online (Sandbox Code Playgroud) 让我们考虑一个用C++ 11编写的模板函数,它迭代一个容器.请排除考虑范围循环语法,因为我正在使用的编译器尚不支持它.
template <typename Container>
void DoSomething(const Container& i_container)
{
// Option #1
for (auto it = std::begin(i_container); it != std::end(i_container); ++it)
{
// do something with *it
}
// Option #2
std::for_each(std::begin(i_container), std::end(i_container),
[] (typename Container::const_reference element)
{
// do something with element
});
}
Run Code Online (Sandbox Code Playgroud)
什么是for loop vs的优缺点std::for_each:
一场表演?(我不希望有任何区别)
b)可读性和可维护性?
在这里,我看到了许多缺点for_each.循环会不会接受c风格的数组.lambda形式参数的声明是如此冗长,不可能在auto那里使用.不可能突破for_each.
在C++之前的11天里,反对for是需要为迭代器指定类型(不再容纳)以及很容易错误地输入循环条件(我从未在10年内做过这样的错误).
作为结论,我for_each的观点与普遍观点相矛盾.我在这里错过了什么?
我似乎在问题和答案中看到比迭代器更多的"for"循环,而不是for_each(),transform()等.Scott Meyers建议使用stl算法,或者至少在2001年做过.当然,使用它们通常意味着将循环体移动到函数或函数对象中.有些人可能觉得这是一种不可接受的并发症,而其他人可能觉得这样可以更好地解决问题.
那么... STL算法应该优于手动循环吗?
我是C++的新手,我正在编写以下代码.我需要遍历调用函数中的所有插件 - testFunction.我知道这在C#中有效,但是这段代码不起作用.任何人都可以指出在C++中正确的方法吗?
#include "stdafx.h"
#include <iostream>
#include "resource.h"
int testFunction(char* tester);
int _tmain()
{
int mainProd=2;
int Addons[]={7,8,9,10};
testFunction(mainProd,Addons);
}
void testFunction(int mainProd,int addons[])
{
for(int x = 0 ; addons.length;++x) ---- Not working
{
std::cout<< addons[x];
}
}
Run Code Online (Sandbox Code Playgroud)
我试图按照以下建议实现矢量
#include "stdafx.h"
#include <iostream>
#include "resource.h"
#include <vector>
void testFunction(std::vector<int> addons);
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> Addons ;
for(int i = 0 ;i<10;++i)
{
Addons.push_back(i);
}
testFunction(Addons);
}
void testFunction(std::vector<int> addons)
{
for(int i =0 ; …Run Code Online (Sandbox Code Playgroud) 所以我正在玩一些C++ 11的功能,我很好奇为什么std :: for_each是有益的.做一个for循环会不会更简单,看起来更干净,还是因为我习惯这样做?
#include <iostream>
#include <tuple>
#include <vector>
#include <algorithm>
typedef std::tuple<int, int> pow_tuple;
pow_tuple pow(int x)
{
return std::make_tuple(x, x*x);
}
void print_values(pow_tuple values)
{
std::cout << std::get<0>(values) << "\t" << std::get<1>(values) << std::endl;
}
int main(int argc, char** argv)
{
std::vector<int> numbers;
for (int i=1; i < 10; i++)
numbers.push_back(i);
std::for_each(numbers.begin(), numbers.end(),
[](int x) { print_values(pow(x)); }
);
std::cout << "Using auto keyword:" << std::endl;
auto values = pow(20);
print_values(values); …Run Code Online (Sandbox Code Playgroud)